content
stringlengths
0
14.9M
filename
stringlengths
44
136
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Get Properties of an Antibiotic #' #' Use these functions to return a specific property of an antibiotic from the [antibiotics] data set. All input values will be evaluated internally with [as.ab()]. #' @param x any (vector of) text that can be coerced to a valid antibiotic drug code with [as.ab()] #' @param tolower a [logical] to indicate whether the first [character] of every output should be transformed to a lower case [character]. This will lead to e.g. "polymyxin B" and not "polymyxin b". #' @param property one of the column names of one of the [antibiotics] data set: `vector_or(colnames(antibiotics), sort = FALSE)`. #' @param language language of the returned text - the default is the current system language (see [get_AMR_locale()]) and can also be set with the [package option][AMR-options] [`AMR_locale`][AMR-options]. Use `language = NULL` or `language = ""` to prevent translation. #' @param administration way of administration, either `"oral"` or `"iv"` #' @param open browse the URL using [utils::browseURL()] #' @param ... in case of [set_ab_names()] and `data` is a [data.frame]: columns to select (supports tidy selection such as `column1:column4`), otherwise other arguments passed on to [as.ab()] #' @param data a [data.frame] of which the columns need to be renamed, or a [character] vector of column names #' @param snake_case a [logical] to indicate whether the names should be in so-called [snake case](https://en.wikipedia.org/wiki/Snake_case): in lower case and all spaces/slashes replaced with an underscore (`_`) #' @param only_first a [logical] to indicate whether only the first ATC code must be returned, with giving preference to J0-codes (i.e., the antimicrobial drug group) #' @details All output [will be translated][translate] where possible. #' #' The function [ab_url()] will return the direct URL to the official WHO website. A warning will be returned if the required ATC code is not available. #' #' The function [set_ab_names()] is a special column renaming function for [data.frame]s. It renames columns names that resemble antimicrobial drugs. It always makes sure that the new column names are unique. If `property = "atc"` is set, preference is given to ATC codes from the J-group. #' @inheritSection as.ab Source #' @rdname ab_property #' @name ab_property #' @return #' - An [integer] in case of [ab_cid()] #' - A named [list] in case of [ab_info()] and multiple [ab_atc()]/[ab_synonyms()]/[ab_tradenames()] #' - A [double] in case of [ab_ddd()] #' - A [data.frame] in case of [set_ab_names()] #' - A [character] in all other cases #' @export #' @seealso [antibiotics] #' @inheritSection AMR Reference Data Publicly Available #' @examples #' # all properties: #' ab_name("AMX") #' ab_atc("AMX") #' ab_cid("AMX") #' ab_synonyms("AMX") #' ab_tradenames("AMX") #' ab_group("AMX") #' ab_atc_group1("AMX") #' ab_atc_group2("AMX") #' ab_url("AMX") #' #' # smart lowercase transformation #' ab_name(x = c("AMC", "PLB")) #' ab_name(x = c("AMC", "PLB"), tolower = TRUE) #' #' # defined daily doses (DDD) #' ab_ddd("AMX", "oral") #' ab_ddd_units("AMX", "oral") #' ab_ddd("AMX", "iv") #' ab_ddd_units("AMX", "iv") #' #' ab_info("AMX") # all properties as a list #' #' # all ab_* functions use as.ab() internally, so you can go from 'any' to 'any': #' ab_atc("AMP") #' ab_group("J01CA01") #' ab_loinc("ampicillin") #' ab_name("21066-6") #' ab_name(6249) #' ab_name("J01CA01") #' #' # spelling from different languages and dyslexia are no problem #' ab_atc("ceftriaxon") #' ab_atc("cephtriaxone") #' ab_atc("cephthriaxone") #' ab_atc("seephthriaaksone") #' #' # use set_ab_names() for renaming columns #' colnames(example_isolates) #' colnames(set_ab_names(example_isolates)) #' colnames(set_ab_names(example_isolates, NIT:VAN)) #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' set_ab_names() #' #' # this does the same: #' example_isolates %>% #' rename_with(set_ab_names) #' #' # set_ab_names() works with any AB property: #' example_isolates %>% #' set_ab_names(property = "atc") #' #' example_isolates %>% #' set_ab_names(where(is.sir)) %>% #' colnames() #' #' example_isolates %>% #' set_ab_names(NIT:VAN) %>% #' colnames() #' } #' } ab_name <- function(x, language = get_AMR_locale(), tolower = FALSE, ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(tolower, allow_class = "logical", has_length = 1) x <- translate_into_language(ab_validate(x = x, property = "name", ...), language = language, only_affect_ab_names = TRUE) if (tolower == TRUE) { # use perl to only transform the first character # as we want "polymyxin B", not "polymyxin b" x <- gsub("^([A-Z])", "\\L\\1", x, perl = TRUE) } x } #' @rdname ab_property #' @export ab_cid <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) ab_validate(x = x, property = "cid", ...) } #' @rdname ab_property #' @export ab_synonyms <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) syns <- ab_validate(x = x, property = "synonyms", ...) names(syns) <- x if (length(syns) == 1) { unname(unlist(syns)) } else { syns } } #' @rdname ab_property #' @export ab_tradenames <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) ab_synonyms(x, ...) } #' @rdname ab_property #' @export ab_group <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) translate_into_language(ab_validate(x = x, property = "group", ...), language = language, only_affect_ab_names = TRUE) } #' @rdname ab_property #' @aliases ATC #' @export ab_atc <- function(x, only_first = FALSE, ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(only_first, allow_class = "logical", has_length = 1) atcs <- ab_validate(x = x, property = "atc", ...) if (only_first == TRUE) { atcs <- vapply( FUN.VALUE = character(1), # get only the first ATC code atcs, function(x) { # try to get the J-group if (any(x %like% "^J")) { x[x %like% "^J"][1L] } else { as.character(x[1L]) } } ) } else if (length(atcs) == 1) { atcs <- unname(unlist(atcs)) } else { names(atcs) <- x } atcs } #' @rdname ab_property #' @export ab_atc_group1 <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) translate_into_language(ab_validate(x = x, property = "atc_group1", ...), language = language, only_affect_ab_names = TRUE) } #' @rdname ab_property #' @export ab_atc_group2 <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) translate_into_language(ab_validate(x = x, property = "atc_group2", ...), language = language, only_affect_ab_names = TRUE) } #' @rdname ab_property #' @export ab_loinc <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) loincs <- ab_validate(x = x, property = "loinc", ...) names(loincs) <- x if (length(loincs) == 1) { unname(unlist(loincs)) } else { loincs } } #' @rdname ab_property #' @export ab_ddd <- function(x, administration = "oral", ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(administration, is_in = c("oral", "iv"), has_length = 1) x <- as.ab(x, ...) ddd_prop <- paste0(administration, "_ddd") out <- ab_validate(x = x, property = ddd_prop) if (any(ab_name(x, language = NULL) %like% "/" & is.na(out))) { warning_( "in `ab_ddd()`: DDDs of some combined products are available for different dose combinations and not (yet) part of the AMR package.", "Please refer to the WHOCC website:\n", "www.whocc.no/ddd/list_of_ddds_combined_products/" ) } out } #' @rdname ab_property #' @export ab_ddd_units <- function(x, administration = "oral", ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(administration, is_in = c("oral", "iv"), has_length = 1) x <- as.ab(x, ...) ddd_prop <- paste0(administration, "_units") out <- ab_validate(x = x, property = ddd_prop) if (any(ab_name(x, language = NULL) %like% "/" & is.na(out))) { warning_( "in `ab_ddd_units()`: DDDs of some combined products are available for different dose combinations and not (yet) part of the AMR package.", "Please refer to the WHOCC website:\n", "www.whocc.no/ddd/list_of_ddds_combined_products/" ) } out } #' @rdname ab_property #' @export ab_info <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) x <- as.ab(x, ...) list( ab = as.character(x), cid = ab_cid(x), name = ab_name(x, language = language), group = ab_group(x, language = language), atc = ab_atc(x), atc_group1 = ab_atc_group1(x, language = language), atc_group2 = ab_atc_group2(x, language = language), tradenames = ab_tradenames(x), loinc = ab_loinc(x), ddd = list( oral = list( amount = ab_ddd(x, administration = "oral"), units = ab_ddd_units(x, administration = "oral") ), iv = list( amount = ab_ddd(x, administration = "iv"), units = ab_ddd_units(x, administration = "iv") ) ) ) } #' @rdname ab_property #' @export ab_url <- function(x, open = FALSE, ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(open, allow_class = "logical", has_length = 1) ab <- as.ab(x = x, ...) atcs <- ab_atc(ab, only_first = TRUE) u <- paste0("https://www.whocc.no/atc_ddd_index/?code=", atcs, "&showdescription=no") u[is.na(atcs)] <- NA_character_ names(u) <- ab_name(ab) NAs <- ab_name(ab, tolower = TRUE, language = NULL)[!is.na(ab) & is.na(atcs)] if (length(NAs) > 0) { warning_("in `ab_url()`: no ATC code available for ", vector_and(NAs, quotes = FALSE), ".") } if (open == TRUE) { if (length(u) > 1 && !is.na(u[1L])) { warning_("in `ab_url()`: only the first URL will be opened, as `browseURL()` only suports one string.") } if (!is.na(u[1L])) { utils::browseURL(u[1L]) } } u } #' @rdname ab_property #' @export ab_property <- function(x, property = "name", language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(property, is_in = colnames(AMR::antibiotics), has_length = 1) language <- validate_language(language) translate_into_language(ab_validate(x = x, property = property, ...), language = language) } #' @rdname ab_property #' @aliases ATC #' @export set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale(), snake_case = NULL) { meet_criteria(data, allow_class = c("data.frame", "character")) meet_criteria(property, is_in = colnames(AMR::antibiotics), has_length = 1, ignore.case = TRUE) language <- validate_language(language) meet_criteria(snake_case, allow_class = "logical", has_length = 1, allow_NULL = TRUE) x_deparsed <- deparse(substitute(data)) if (length(x_deparsed) > 1 || any(x_deparsed %unlike% "[a-z]+")) { x_deparsed <- "your_data" } property <- tolower(property) if (is.null(snake_case)) { snake_case <- property == "name" } if (is.data.frame(data)) { if (tryCatch(length(c(...)) > 1, error = function(e) TRUE)) { df <- tryCatch(suppressWarnings(pm_select(data, ...)), error = function(e) { data[, c(...), drop = FALSE] } ) } else if (tryCatch(is.character(c(...)), error = function(e) FALSE)) { df <- data[, c(...), drop = FALSE] } else { df <- data } vars <- get_column_abx(df, info = FALSE, only_sir_columns = FALSE, sort = FALSE, fn = "set_ab_names") if (length(vars) == 0) { message_("No columns with antibiotic results found for `set_ab_names()`, leaving names unchanged.") return(data) } } else { # quickly get antibiotic drug codes vars_ab <- as.ab(data, fast_mode = TRUE) vars <- data[!is.na(vars_ab)] } x <- vapply( FUN.VALUE = character(1), ab_property(vars, property = property, language = language), function(x) { if (property == "atc") { # try to get the J-group if (any(x %like% "^J")) { x[x %like% "^J"][1L] } else { as.character(x[1L]) } } else { as.character(x[1L]) } }, USE.NAMES = FALSE ) if (any(x %in% c("", NA))) { warning_( "in `set_ab_names()`: no ", property, " found for column(s): ", vector_and(vars[x %in% c("", NA)], sort = FALSE) ) x[x %in% c("", NA)] <- vars[x %in% c("", NA)] } if (snake_case == TRUE) { x <- tolower(gsub("[^a-zA-Z0-9]+", "_", x)) } if (anyDuplicated(x)) { # very hacky way of adding the index to each duplicate # so "Amoxicillin", "Amoxicillin", "Amoxicillin" # will be "Amoxicillin", "Amoxicillin_2", "Amoxicillin_3" invisible(lapply( unique(x), function(u) { dups <- which(x == u) if (length(dups) > 1) { # there are duplicates dup_add_int <- dups[2:length(dups)] x[dup_add_int] <<- paste0(x[dup_add_int], "_", 2:length(dups)) } } )) } if (is.data.frame(data)) { colnames(data)[colnames(data) %in% vars] <- x data } else { data[which(!is.na(vars_ab))] <- x data } } ab_validate <- function(x, property, ...) { if (tryCatch(all(x[!is.na(x)] %in% AMR_env$AB_lookup$ab), error = function(e) FALSE)) { # special case for ab_* functions where class is already 'ab' x <- AMR_env$AB_lookup[match(x, AMR_env$AB_lookup$ab), property, drop = TRUE] } else { # try to catch an error when inputting an invalid argument # so the 'call.' can be set to FALSE tryCatch(x[1L] %in% AMR_env$AB_lookup[1, property, drop = TRUE], error = function(e) stop(e$message, call. = FALSE) ) if (!all(x %in% AMR_env$AB_lookup[, property, drop = TRUE])) { x <- as.ab(x, ...) if (all(is.na(x)) && is.list(AMR_env$AB_lookup[, property, drop = TRUE])) { x <- rep(NA_character_, length(x)) } else { x <- AMR_env$AB_lookup[match(x, AMR_env$AB_lookup$ab), property, drop = TRUE] } } } if (property == "ab") { return(set_clean_class(x, new_class = c("ab", "character"))) } else if (property == "cid") { return(as.integer(x)) } else if (property %like% "ddd") { return(as.double(x)) } else { x[is.na(x)] <- NA return(x) } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/ab_property.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Antibiotic Selectors #' #' @description These functions allow for filtering rows and selecting columns based on antibiotic test results that are of a specific antibiotic class or group (according to the [antibiotics] data set), without the need to define the columns or antibiotic abbreviations. #' #' In short, if you have a column name that resembles an antimicrobial drug, it will be picked up by any of these functions that matches its pharmaceutical class: "cefazolin", "kefzol", "CZO" and "J01DB04" will all be picked up by [cephalosporins()]. #' @param ab_class an antimicrobial class or a part of it, such as `"carba"` and `"carbapenems"`. The columns `group`, `atc_group1` and `atc_group2` of the [antibiotics] data set will be searched (case-insensitive) for this value. #' @param filter an [expression] to be evaluated in the [antibiotics] data set, such as `name %like% "trim"` #' @param only_sir_columns a [logical] to indicate whether only columns of class `sir` must be selected (default is `FALSE`), see [as.sir()] #' @param only_treatable a [logical] to indicate whether antimicrobial drugs should be excluded that are only for laboratory tests (default is `TRUE`), such as gentamicin-high (`GEH`) and imipenem/EDTA (`IPE`) #' @param ... ignored, only in place to allow future extensions #' @details #' These functions can be used in data set calls for selecting columns and filtering rows. They work with base \R, the Tidyverse, and `data.table`. They are heavily inspired by the [Tidyverse selection helpers][tidyselect::language] such as [`everything()`][tidyselect::everything()], but are not limited to `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.) 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. #' #' The [ab_class()] function can be used to filter/select on a manually defined antibiotic class. It searches for results in the [antibiotics] data set within the columns `group`, `atc_group1` and `atc_group2`. #' @section Full list of supported (antibiotic) classes: #' #' `r paste0(" * ", na.omit(sapply(DEFINED_AB_GROUPS, function(ab) ifelse(tolower(gsub("^AB_", "", ab)) %in% ls(envir = asNamespace("AMR")), paste0("[", tolower(gsub("^AB_", "", ab)), "()] can select: \\cr ", vector_and(paste0(ab_name(eval(parse(text = ab), envir = asNamespace("AMR")), language = NULL, tolower = TRUE), " (", eval(parse(text = ab), envir = asNamespace("AMR")), ")"), quotes = FALSE, sort = TRUE)), character(0)), USE.NAMES = FALSE)), "\n", collapse = "")` #' @rdname antibiotic_class_selectors #' @name antibiotic_class_selectors #' @return (internally) a [character] vector of column names, with additional class `"ab_selector"` #' @export #' @inheritSection AMR Reference Data Publicly Available #' @examples #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates. #' example_isolates #' #' #' # Examples sections below are split into 'base R', 'dplyr', and 'data.table': #' #' #' # base R ------------------------------------------------------------------ #' #' # select columns 'IPM' (imipenem) and 'MEM' (meropenem) #' example_isolates[, carbapenems()] #' #' # select columns 'mo', 'AMK', 'GEN', 'KAN' and 'TOB' #' example_isolates[, c("mo", aminoglycosides())] #' #' # select only antibiotic columns with DDDs for oral treatment #' example_isolates[, administrable_per_os()] #' #' # filter using any() or all() #' example_isolates[any(carbapenems() == "R"), ] #' subset(example_isolates, any(carbapenems() == "R")) #' #' # filter on any or all results in the carbapenem columns (i.e., IPM, MEM): #' example_isolates[any(carbapenems()), ] #' example_isolates[all(carbapenems()), ] #' #' # filter with multiple antibiotic selectors using c() #' example_isolates[all(c(carbapenems(), aminoglycosides()) == "R"), ] #' #' # filter + select in one go: get penicillins in carbapenem-resistant strains #' example_isolates[any(carbapenems() == "R"), penicillins()] #' #' # You can combine selectors with '&' to be more specific. For example, #' # penicillins() would select benzylpenicillin ('peni G') and #' # administrable_per_os() would select erythromycin. Yet, when combined these #' # drugs are both omitted since benzylpenicillin is not administrable per os #' # and erythromycin is not a penicillin: #' example_isolates[, penicillins() & administrable_per_os()] #' #' # ab_selector() applies a filter in the `antibiotics` data set and is thus #' # very flexible. For instance, to select antibiotic columns with an oral DDD #' # of at least 1 gram: #' example_isolates[, ab_selector(oral_ddd > 1 & oral_units == "g")] #' #' \donttest{ #' # dplyr ------------------------------------------------------------------- #' #' if (require("dplyr")) { #' tibble(kefzol = random_sir(5)) %>% #' select(cephalosporins()) #' } #' #' if (require("dplyr")) { #' # get AMR for all aminoglycosides e.g., per ward: #' example_isolates %>% #' group_by(ward) %>% #' summarise(across(aminoglycosides(), resistance)) #' } #' if (require("dplyr")) { #' # You can combine selectors with '&' to be more specific: #' example_isolates %>% #' select(penicillins() & administrable_per_os()) #' } #' if (require("dplyr")) { #' # get AMR for only drugs that matter - no intrinsic resistance: #' example_isolates %>% #' filter(mo_genus() %in% c("Escherichia", "Klebsiella")) %>% #' group_by(ward) %>% #' summarise(across(not_intrinsic_resistant(), resistance)) #' } #' if (require("dplyr")) { #' # get susceptibility for antibiotics whose name contains "trim": #' example_isolates %>% #' filter(first_isolate()) %>% #' group_by(ward) %>% #' summarise(across(ab_selector(name %like% "trim"), susceptibility)) #' } #' if (require("dplyr")) { #' # this will select columns 'IPM' (imipenem) and 'MEM' (meropenem): #' example_isolates %>% #' select(carbapenems()) #' } #' if (require("dplyr")) { #' # this will select columns 'mo', 'AMK', 'GEN', 'KAN' and 'TOB': #' example_isolates %>% #' select(mo, aminoglycosides()) #' } #' if (require("dplyr")) { #' # any() and all() work in dplyr's filter() too: #' example_isolates %>% #' filter( #' any(aminoglycosides() == "R"), #' all(cephalosporins_2nd() == "R") #' ) #' } #' if (require("dplyr")) { #' # also works with c(): #' example_isolates %>% #' filter(any(c(carbapenems(), aminoglycosides()) == "R")) #' } #' if (require("dplyr")) { #' # not setting any/all will automatically apply all(): #' example_isolates %>% #' filter(aminoglycosides() == "R") #' } #' if (require("dplyr")) { #' # this will select columns 'mo' and all antimycobacterial drugs ('RIF'): #' example_isolates %>% #' select(mo, ab_class("mycobact")) #' } #' if (require("dplyr")) { #' # get bug/drug combinations for only glycopeptides in Gram-positives: #' example_isolates %>% #' filter(mo_is_gram_positive()) %>% #' select(mo, glycopeptides()) %>% #' bug_drug_combinations() %>% #' format() #' } #' if (require("dplyr")) { #' data.frame( #' some_column = "some_value", #' J01CA01 = "S" #' ) %>% # ATC code of ampicillin #' select(penicillins()) # only the 'J01CA01' column will be selected #' } #' if (require("dplyr")) { #' # with recent versions of dplyr, this is all equal: #' x <- example_isolates[carbapenems() == "R", ] #' y <- example_isolates %>% filter(carbapenems() == "R") #' z <- example_isolates %>% filter(if_all(carbapenems(), ~ .x == "R")) #' identical(x, y) && identical(y, z) #' } #' #' #' # data.table -------------------------------------------------------------- #' #' # data.table is supported as well, just use it in the same way as with #' # base R, but add `with = FALSE` if using a single AB selector. #' #' if (require("data.table")) { #' dt <- as.data.table(example_isolates) #' #' # this does not work, it returns column *names* #' dt[, carbapenems()] #' } #' if (require("data.table")) { #' # so `with = FALSE` is required #' dt[, carbapenems(), with = FALSE] #' } #' #' # for multiple selections or AB selectors, `with = FALSE` is not needed: #' if (require("data.table")) { #' dt[, c("mo", aminoglycosides())] #' } #' if (require("data.table")) { #' dt[, c(carbapenems(), aminoglycosides())] #' } #' #' # row filters are also supported: #' if (require("data.table")) { #' dt[any(carbapenems() == "S"), ] #' } #' if (require("data.table")) { #' dt[any(carbapenems() == "S"), penicillins(), with = FALSE] #' } #' } ab_class <- function(ab_class, only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(ab_class, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec(NULL, only_sir_columns = only_sir_columns, ab_class_args = ab_class, only_treatable = only_treatable) } #' @rdname antibiotic_class_selectors #' @details The [ab_selector()] function can be used to internally filter the [antibiotics] data set on any results, see *Examples*. It allows for filtering on a (part of) a certain name, and/or a group name or even a minimum of DDDs for oral treatment. This function yields the highest flexibility, but is also the least user-friendly, since it requires a hard-coded filter to set. #' @export ab_selector <- function(filter, only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } # get_current_data() has to run each time, for cases where e.g., filter() and select() are used in same call # but it only takes a couple of milliseconds vars_df <- get_current_data(arg_name = NA, call = -2) # to improve speed, get_column_abx() will only run once when e.g. in a select or group call ab_in_data <- get_column_abx(vars_df, info = FALSE, only_sir_columns = only_sir_columns, sort = FALSE, fn = "ab_selector" ) call <- substitute(filter) agents <- tryCatch(AMR_env$AB_lookup[which(eval(call, envir = AMR_env$AB_lookup)), "ab", drop = TRUE], error = function(e) stop_(e$message, call = -5) ) agents <- ab_in_data[ab_in_data %in% agents] message_agent_names( function_name = "ab_selector", agents = agents, ab_group = NULL, examples = "", call = call ) structure(unname(agents), class = c("ab_selector", "character") ) } #' @rdname antibiotic_class_selectors #' @export aminoglycosides <- function(only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("aminoglycosides", only_sir_columns = only_sir_columns, only_treatable = only_treatable) } #' @rdname antibiotic_class_selectors #' @export aminopenicillins <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("aminopenicillins", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export antifungals <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("antifungals", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export antimycobacterials <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("antimycobacterials", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export betalactams <- function(only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("betalactams", only_sir_columns = only_sir_columns, only_treatable = only_treatable) } #' @rdname antibiotic_class_selectors #' @export carbapenems <- function(only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("carbapenems", only_sir_columns = only_sir_columns, only_treatable = only_treatable) } #' @rdname antibiotic_class_selectors #' @export cephalosporins <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export cephalosporins_1st <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins_1st", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export cephalosporins_2nd <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins_2nd", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export cephalosporins_3rd <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins_3rd", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export cephalosporins_4th <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins_4th", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export cephalosporins_5th <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("cephalosporins_5th", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export fluoroquinolones <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("fluoroquinolones", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export glycopeptides <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("glycopeptides", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export lincosamides <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("lincosamides", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export lipoglycopeptides <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("lipoglycopeptides", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export macrolides <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("macrolides", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export oxazolidinones <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("oxazolidinones", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export penicillins <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("penicillins", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export polymyxins <- function(only_sir_columns = FALSE, only_treatable = TRUE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(only_treatable, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("polymyxins", only_sir_columns = only_sir_columns, only_treatable = only_treatable) } #' @rdname antibiotic_class_selectors #' @export streptogramins <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("streptogramins", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export quinolones <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("quinolones", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export tetracyclines <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("tetracyclines", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export trimethoprims <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("trimethoprims", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @export ureidopenicillins <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } ab_select_exec("ureidopenicillins", only_sir_columns = only_sir_columns) } #' @rdname antibiotic_class_selectors #' @details The [administrable_per_os()] and [administrable_iv()] functions also rely on the [antibiotics] data set - antibiotic columns will be matched where a DDD (defined daily dose) for resp. oral and IV treatment is available in the [antibiotics] data set. #' @export administrable_per_os <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) # get_current_data() has to run each time, for cases where e.g., filter() and select() are used in same call # but it only takes a couple of milliseconds vars_df <- get_current_data(arg_name = NA, call = -2) # to improve speed, get_column_abx() will only run once when e.g. in a select or group call ab_in_data <- get_column_abx(vars_df, info = FALSE, only_sir_columns = only_sir_columns, sort = FALSE, fn = "administrable_per_os" ) agents_all <- AMR_env$AB_lookup[which(!is.na(AMR_env$AB_lookup$oral_ddd)), "ab", drop = TRUE] agents <- AMR_env$AB_lookup[which(AMR_env$AB_lookup$ab %in% ab_in_data & !is.na(AMR_env$AB_lookup$oral_ddd)), "ab", drop = TRUE] agents <- ab_in_data[ab_in_data %in% agents] message_agent_names( function_name = "administrable_per_os", agents = agents, ab_group = "administrable_per_os", examples = paste0( " (such as ", vector_or( ab_name( sample(agents_all, size = min(5, length(agents_all)), replace = FALSE ), tolower = TRUE, language = NULL ), quotes = FALSE ), ")" ) ) structure(unname(agents), class = c("ab_selector", "character") ) } #' @rdname antibiotic_class_selectors #' @export administrable_iv <- function(only_sir_columns = FALSE, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) # get_current_data() has to run each time, for cases where e.g., filter() and select() are used in same call # but it only takes a couple of milliseconds vars_df <- get_current_data(arg_name = NA, call = -2) # to improve speed, get_column_abx() will only run once when e.g. in a select or group call ab_in_data <- get_column_abx(vars_df, info = FALSE, only_sir_columns = only_sir_columns, sort = FALSE, fn = "administrable_iv" ) agents_all <- AMR_env$AB_lookup[which(!is.na(AMR_env$AB_lookup$iv_ddd)), "ab", drop = TRUE] agents <- AMR_env$AB_lookup[which(AMR_env$AB_lookup$ab %in% ab_in_data & !is.na(AMR_env$AB_lookup$iv_ddd)), "ab", drop = TRUE] agents <- ab_in_data[ab_in_data %in% agents] message_agent_names( function_name = "administrable_iv", agents = agents, ab_group = "administrable_iv", examples = "" ) structure(unname(agents), class = c("ab_selector", "character") ) } #' @rdname antibiotic_class_selectors #' @inheritParams eucast_rules #' @details The [not_intrinsic_resistant()] function can be used to only select antibiotic columns that pose no intrinsic resistance for the microorganisms in the data set. For example, if a data set contains only microorganism codes or names of *E. coli* and *K. pneumoniae* and contains a column "vancomycin", this column will be removed (or rather, unselected) using this function. It currently applies `r format_eucast_version_nr(names(EUCAST_VERSION_EXPERT_RULES[1]))` to determine intrinsic resistance, using the [eucast_rules()] function internally. Because of this determination, this function is quite slow in terms of performance. #' @export not_intrinsic_resistant <- function(only_sir_columns = FALSE, col_mo = NULL, version_expertrules = 3.3, ...) { meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) # get_current_data() has to run each time, for cases where e.g., filter() and select() are used in same call # but it only takes a couple of milliseconds vars_df <- get_current_data(arg_name = NA, call = -2) # to improve speed, get_column_abx() will only run once when e.g. in a select or group call ab_in_data <- get_column_abx(vars_df, info = FALSE, only_sir_columns = only_sir_columns, sort = FALSE, fn = "not_intrinsic_resistant" ) # intrinsic vars vars_df_R <- tryCatch( sapply( eucast_rules(vars_df, col_mo = col_mo, version_expertrules = version_expertrules, rules = "expert", info = FALSE ), function(col) { tryCatch(!any(is.na(col)) && all(col == "R"), error = function(e) FALSE ) } ), error = function(e) stop_("in not_intrinsic_resistant(): ", e$message, call = FALSE) ) agents <- ab_in_data[ab_in_data %in% names(vars_df_R[which(vars_df_R)])] if (length(agents) > 0 && message_not_thrown_before("not_intrinsic_resistant", sort(agents))) { agents_formatted <- paste0("'", font_bold(agents, collapse = NULL), "'") agents_names <- ab_name(names(agents), tolower = TRUE, language = NULL) need_name <- generalise_antibiotic_name(agents) != generalise_antibiotic_name(agents_names) agents_formatted[need_name] <- paste0(agents_formatted[need_name], " (", agents_names[need_name], ")") message_( "For `not_intrinsic_resistant()` removing ", ifelse(length(agents) == 1, "column ", "columns "), vector_and(agents_formatted, quotes = FALSE, sort = FALSE) ) } vars_df_R <- names(vars_df_R)[which(!vars_df_R)] # find columns that are abx, but also intrinsic R out <- unname(intersect(ab_in_data, vars_df_R)) structure(out, class = c("ab_selector", "character") ) } ab_select_exec <- function(function_name, only_sir_columns = FALSE, only_treatable = FALSE, ab_class_args = NULL) { # get_current_data() has to run each time, for cases where e.g., filter() and select() are used in same call # but it only takes a couple of milliseconds vars_df <- get_current_data(arg_name = NA, call = -3) # to improve speed, get_column_abx() will only run once when e.g. in a select or group call ab_in_data <- get_column_abx(vars_df, info = FALSE, only_sir_columns = only_sir_columns, sort = FALSE, fn = function_name ) # untreatable drugs if (only_treatable == TRUE) { untreatable <- AMR_env$AB_lookup[which(AMR_env$AB_lookup$name %like% "-high|EDTA|polysorbate|macromethod|screening|/nacubactam"), "ab", drop = TRUE] if (any(untreatable %in% names(ab_in_data))) { if (message_not_thrown_before(function_name, "ab_class", "untreatable", entire_session = TRUE)) { warning_( "in `", function_name, "()`: some drugs were ignored since they cannot be used for treating patients: ", vector_and( ab_name(names(ab_in_data)[names(ab_in_data) %in% untreatable], language = NULL, tolower = TRUE ), quotes = FALSE, sort = TRUE ), ". They can be included using `", function_name, "(only_treatable = FALSE)`. ", "This warning will be shown once per session." ) } ab_in_data <- ab_in_data[!names(ab_in_data) %in% untreatable] } } if (length(ab_in_data) == 0) { message_("No antimicrobial drugs found in the data.") return(NULL) } if (is.null(ab_class_args) || isTRUE(function_name %in% c("antifungals", "antimycobacterials"))) { ab_group <- NULL if (isTRUE(function_name == "antifungals")) { abx <- AMR_env$AB_lookup$ab[which(AMR_env$AB_lookup$group == "Antifungals")] } else if (isTRUE(function_name == "antimycobacterials")) { abx <- AMR_env$AB_lookup$ab[which(AMR_env$AB_lookup$group == "Antimycobacterials")] } else { # their upper case equivalent are vectors with class 'ab', created in data-raw/_pre_commit_hook.R # carbapenems() gets its codes from AMR:::AB_CARBAPENEMS abx <- get(paste0("AB_", toupper(function_name)), envir = asNamespace("AMR")) # manually added codes from add_custom_antimicrobials() must also be supported if (length(AMR_env$custom_ab_codes) > 0) { custom_ab <- AMR_env$AB_lookup[which(AMR_env$AB_lookup$ab %in% AMR_env$custom_ab_codes), ] check_string <- paste0(custom_ab$group, custom_ab$atc_group1, custom_ab$atc_group2) if (function_name == "betalactams") { find_group <- "beta-lactams" } else if (function_name %like% "cephalosporins_") { find_group <- gsub("_(.*)$", paste0(" (\\1 gen.)"), function_name) } else { find_group <- function_name } abx <- c(abx, custom_ab$ab[which(check_string %like% find_group)]) } ab_group <- function_name } examples <- paste0(" (such as ", vector_or( ab_name(sample(abx, size = min(2, length(abx)), replace = FALSE), tolower = TRUE, language = NULL ), quotes = FALSE ), ")") } else { # this for the 'manual' ab_class() function abx <- subset( AMR_env$AB_lookup, group %like% ab_class_args | atc_group1 %like% ab_class_args | atc_group2 %like% ab_class_args )$ab ab_group <- find_ab_group(ab_class_args) function_name <- "ab_class" examples <- paste0(" (such as ", find_ab_names(ab_class_args, 2), ")") } # get the columns with a group names in the chosen ab class agents <- ab_in_data[names(ab_in_data) %in% abx] message_agent_names( function_name = function_name, agents = agents, ab_group = ab_group, examples = examples, ab_class_args = ab_class_args ) structure(unname(agents), class = c("ab_selector", "character") ) } #' @method c ab_selector #' @export #' @noRd c.ab_selector <- function(...) { structure(unlist(lapply(list(...), as.character)), class = c("ab_selector", "character") ) } all_any_ab_selector <- function(type, ..., na.rm = TRUE) { cols_ab <- c(...) result <- cols_ab[toupper(cols_ab) %in% c("S", "I", "R")] if (length(result) == 0) { message_("Filtering ", type, " of columns ", vector_and(font_bold(cols_ab, collapse = NULL), quotes = "'"), ' to contain value "S", "I" or "R"') result <- c("S", "I", "R") } cols_ab <- cols_ab[!cols_ab %in% result] df <- get_current_data(arg_name = NA, call = -3) if (type == "all") { scope_fn <- all } else { scope_fn <- any } x_transposed <- as.list(as.data.frame(t(df[, cols_ab, drop = FALSE]), stringsAsFactors = FALSE)) vapply( FUN.VALUE = logical(1), X = x_transposed, FUN = function(y) scope_fn(y %in% result, na.rm = na.rm), USE.NAMES = FALSE ) } #' @method all ab_selector #' @export #' @noRd all.ab_selector <- function(..., na.rm = FALSE) { all_any_ab_selector("all", ..., na.rm = na.rm) } #' @method any ab_selector #' @export #' @noRd any.ab_selector <- function(..., na.rm = FALSE) { all_any_ab_selector("any", ..., na.rm = na.rm) } #' @method all ab_selector_any_all #' @export #' @noRd all.ab_selector_any_all <- function(..., na.rm = FALSE) { # this is all() on a logical vector from `==.ab_selector` or `!=.ab_selector` # e.g., example_isolates %>% filter(all(carbapenems() == "R")) # so just return the vector as is, only correcting for na.rm out <- unclass(c(...)) if (isTRUE(na.rm)) { out <- out[!is.na(out)] } out } #' @method any ab_selector_any_all #' @export #' @noRd any.ab_selector_any_all <- function(..., na.rm = FALSE) { # this is any() on a logical vector from `==.ab_selector` or `!=.ab_selector` # e.g., example_isolates %>% filter(any(carbapenems() == "R")) # so just return the vector as is, only correcting for na.rm out <- unclass(c(...)) if (isTRUE(na.rm)) { out <- out[!is.na(out)] } out } #' @method == ab_selector #' @export #' @noRd `==.ab_selector` <- function(e1, e2) { calls <- as.character(match.call()) fn_name <- calls[2] fn_name <- gsub("^(c\\()(.*)(\\))$", "\\2", fn_name) if (is_any(fn_name)) { type <- "any" } else if (is_all(fn_name)) { type <- "all" } else { type <- "all" if (length(e1) > 1) { message_( "Assuming a filter on ", type, " ", length(e1), " ", gsub("[\\(\\)]", "", fn_name), ". Wrap around `all()` or `any()` to prevent this note." ) } } structure(all_any_ab_selector(type = type, e1, e2), class = c("ab_selector_any_all", "logical") ) } #' @method != ab_selector #' @export #' @noRd `!=.ab_selector` <- function(e1, e2) { calls <- as.character(match.call()) fn_name <- calls[2] fn_name <- gsub("^(c\\()(.*)(\\))$", "\\2", fn_name) if (is_any(fn_name)) { type <- "any" } else if (is_all(fn_name)) { type <- "all" } else { type <- "all" if (length(e1) > 1) { message_( "Assuming a filter on ", type, " ", length(e1), " ", gsub("[\\(\\)]", "", fn_name), ". Wrap around `all()` or `any()` to prevent this note." ) } } # this is `!=`, so turn around the values sir <- c("S", "I", "R") e2 <- sir[sir != e2] structure(all_any_ab_selector(type = type, e1, e2), class = c("ab_selector_any_all", "logical") ) } #' @method & ab_selector #' @export #' @noRd `&.ab_selector` <- function(e1, e2) { # this is only required for base R, since tidyselect has already implemented this # e.g., for: example_isolates[, penicillins() & administrable_per_os()] structure(intersect(unclass(e1), unclass(e2)), class = c("ab_selector", "character") ) } #' @method | ab_selector #' @export #' @noRd `|.ab_selector` <- function(e1, e2) { # this is only required for base R, since tidyselect has already implemented this # e.g., for: example_isolates[, penicillins() | administrable_per_os()] structure(union(unclass(e1), unclass(e2)), class = c("ab_selector", "character") ) } is_any <- function(el1) { syscalls <- paste0(trimws2(deparse(sys.calls())), collapse = " ") el1 <- gsub("(.*),.*", "\\1", el1) syscalls %like% paste0("[^_a-zA-Z0-9]any\\(", "(c\\()?", el1) } is_all <- function(el1) { syscalls <- paste0(trimws2(deparse(sys.calls())), collapse = " ") el1 <- gsub("(.*),.*", "\\1", el1) syscalls %like% paste0("[^_a-zA-Z0-9]all\\(", "(c\\()?", el1) } find_ab_group <- function(ab_class_args) { ab_class_args <- gsub("[^a-zA-Z0-9]", ".*", ab_class_args) AMR_env$AB_lookup %pm>% subset(group %like% ab_class_args | atc_group1 %like% ab_class_args | atc_group2 %like% ab_class_args) %pm>% pm_pull(group) %pm>% unique() %pm>% tolower() %pm>% sort() %pm>% paste(collapse = "/") } find_ab_names <- function(ab_group, n = 3) { ab_group <- gsub("[^a-zA-Z|0-9]", ".*", ab_group) # try popular first, they have DDDs drugs <- AMR_env$AB_lookup[which((!is.na(AMR_env$AB_lookup$iv_ddd) | !is.na(AMR_env$AB_lookup$oral_ddd)) & AMR_env$AB_lookup$name %unlike% " " & AMR_env$AB_lookup$group %like% ab_group & AMR_env$AB_lookup$ab %unlike% "[0-9]$"), ]$name if (length(drugs) < n) { # now try it all drugs <- AMR_env$AB_lookup[which((AMR_env$AB_lookup$group %like% ab_group | AMR_env$AB_lookup$atc_group1 %like% ab_group | AMR_env$AB_lookup$atc_group2 %like% ab_group) & AMR_env$AB_lookup$ab %unlike% "[0-9]$"), ]$name } if (length(drugs) == 0) { return("??") } vector_or( ab_name(sample(drugs, size = min(n, length(drugs)), replace = FALSE), tolower = TRUE, language = NULL ), quotes = FALSE ) } message_agent_names <- function(function_name, agents, ab_group = NULL, examples = "", ab_class_args = NULL, call = NULL) { if (message_not_thrown_before(function_name, sort(agents))) { if (length(agents) == 0) { if (is.null(ab_group)) { message_("For `", function_name, "()` no antimicrobial drugs found", examples, ".") } else if (ab_group == "administrable_per_os") { message_("No orally administrable drugs found", examples, ".") } else if (ab_group == "administrable_iv") { message_("No IV administrable drugs found", examples, ".") } else { message_("No antimicrobial drugs of class '", ab_group, "' found", examples, ".") } } else { agents_formatted <- paste0("'", font_bold(agents, collapse = NULL), "'") agents_names <- ab_name(names(agents), tolower = TRUE, language = NULL) need_name <- generalise_antibiotic_name(agents) != generalise_antibiotic_name(agents_names) agents_formatted[need_name] <- paste0(agents_formatted[need_name], " (", agents_names[need_name], ")") message_( "For `", function_name, "(", ifelse(function_name == "ab_class", paste0("\"", ab_class_args, "\""), ifelse(!is.null(call), paste0(deparse(call), collapse = " "), "" ) ), ")` using ", ifelse(length(agents) == 1, "column ", "columns "), vector_and(agents_formatted, quotes = FALSE, sort = FALSE) ) } } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/ab_selectors.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Age in Years of Individuals #' #' Calculates age in years based on a reference date, which is the system date at default. #' @param x date(s), [character] (vectors) will be coerced with [as.POSIXlt()] #' @param reference reference date(s) (default is today), [character] (vectors) will be coerced with [as.POSIXlt()] #' @param exact a [logical] to indicate whether age calculation should be exact, i.e. with decimals. It divides the number of days of [year-to-date](https://en.wikipedia.org/wiki/Year-to-date) (YTD) of `x` by the number of days in the year of `reference` (either 365 or 366). #' @param na.rm a [logical] to indicate whether missing values should be removed #' @param ... arguments passed on to [as.POSIXlt()], such as `origin` #' @details Ages below 0 will be returned as `NA` with a warning. Ages above 120 will only give a warning. #' #' This function vectorises over both `x` and `reference`, meaning that either can have a length of 1 while the other argument has a larger length. #' @return An [integer] (no decimals) if `exact = FALSE`, a [double] (with decimals) otherwise #' @seealso To split ages into groups, use the [age_groups()] function. #' @export #' @examples #' # 10 random pre-Y2K birth dates #' df <- data.frame(birth_date = as.Date("2000-01-01") - runif(10) * 25000) #' #' # add ages #' df$age <- age(df$birth_date) #' #' # add exact ages #' df$age_exact <- age(df$birth_date, exact = TRUE) #' #' # add age at millenium switch #' df$age_at_y2k <- age(df$birth_date, "2000-01-01") #' #' df age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) { meet_criteria(x, allow_class = c("character", "Date", "POSIXt")) meet_criteria(reference, allow_class = c("character", "Date", "POSIXt")) meet_criteria(exact, allow_class = "logical", has_length = 1) meet_criteria(na.rm, allow_class = "logical", has_length = 1) if (length(x) != length(reference)) { if (length(x) == 1) { x <- rep(x, length(reference)) } else if (length(reference) == 1) { reference <- rep(reference, length(x)) } else { stop_("`x` and `reference` must be of same length, or `reference` must be of length 1.") } } x <- as.POSIXlt(x, ...) reference <- as.POSIXlt(reference, ...) # from https://stackoverflow.com/a/25450756/4575331 years_gap <- reference$year - x$year ages <- ifelse(reference$mon < x$mon | (reference$mon == x$mon & reference$mday < x$mday), as.integer(years_gap - 1), as.integer(years_gap) ) # add decimals if (exact == TRUE) { # get dates of `x` when `x` would have the year of `reference` x_in_reference_year <- as.POSIXlt( paste0( format(as.Date(reference), "%Y"), format(as.Date(x), "-%m-%d") ), format = "%Y-%m-%d" ) # get differences in days n_days_x_rest <- as.double(difftime(as.Date(reference), as.Date(x_in_reference_year), units = "days" )) # get numbers of days the years of `reference` has for a reliable denominator n_days_reference_year <- as.POSIXlt(paste0(format(as.Date(reference), "%Y"), "-12-31"), format = "%Y-%m-%d" )$yday + 1 # add decimal parts of year mod <- n_days_x_rest / n_days_reference_year # negative mods are cases where `x_in_reference_year` > `reference` - so 'add' a year mod[!is.na(mod) & mod < 0] <- mod[!is.na(mod) & mod < 0] + 1 # and finally add to ages ages <- ages + mod } if (any(ages < 0, na.rm = TRUE)) { ages[!is.na(ages) & ages < 0] <- NA warning_("in `age()`: NAs introduced for ages below 0.") } if (any(ages > 120, na.rm = TRUE)) { warning_("in `age()`: some ages are above 120.") } if (isTRUE(na.rm)) { ages <- ages[!is.na(ages)] } if (exact == TRUE) { as.double(ages) } else { as.integer(ages) } } #' Split Ages into Age Groups #' #' Split ages into age groups defined by the `split` argument. This allows for easier demographic (antimicrobial resistance) analysis. #' @param x age, e.g. calculated with [age()] #' @param split_at values to split `x` at - the default is age groups 0-11, 12-24, 25-54, 55-74 and 75+. See *Details*. #' @param na.rm a [logical] to indicate whether missing values should be removed #' @details To split ages, the input for the `split_at` argument can be: #' #' * A [numeric] vector. A value of e.g. `c(10, 20)` will split `x` on 0-9, 10-19 and 20+. A value of only `50` will split `x` on 0-49 and 50+. #' The default is to split on young children (0-11), youth (12-24), young adults (25-54), middle-aged adults (55-74) and elderly (75+). #' * A character: #' - `"children"` or `"kids"`, equivalent of: `c(0, 1, 2, 4, 6, 13, 18)`. This will split on 0, 1, 2-3, 4-5, 6-12, 13-17 and 18+. #' - `"elderly"` or `"seniors"`, equivalent of: `c(65, 75, 85)`. This will split on 0-64, 65-74, 75-84, 85+. #' - `"fives"`, equivalent of: `1:20 * 5`. This will split on 0-4, 5-9, ..., 95-99, 100+. #' - `"tens"`, equivalent of: `1:10 * 10`. This will split on 0-9, 10-19, ..., 90-99, 100+. #' @return Ordered [factor] #' @seealso To determine ages, based on one or more reference dates, use the [age()] function. #' @export #' @examples #' ages <- c(3, 8, 16, 54, 31, 76, 101, 43, 21) #' #' # split into 0-49 and 50+ #' age_groups(ages, 50) #' #' # split into 0-19, 20-49 and 50+ #' age_groups(ages, c(20, 50)) #' #' # split into groups of ten years #' age_groups(ages, 1:10 * 10) #' age_groups(ages, split_at = "tens") #' #' # split into groups of five years #' age_groups(ages, 1:20 * 5) #' age_groups(ages, split_at = "fives") #' #' # split specifically for children #' age_groups(ages, c(1, 2, 4, 6, 13, 18)) #' age_groups(ages, "children") #' #' \donttest{ #' # resistance of ciprofloxacin per age group #' if (require("dplyr") && require("ggplot2")) { #' example_isolates %>% #' filter_first_isolate() %>% #' filter(mo == as.mo("Escherichia coli")) %>% #' group_by(age_group = age_groups(age)) %>% #' select(age_group, CIP) %>% #' ggplot_sir( #' x = "age_group", #' minimum = 0, #' x.title = "Age Group", #' title = "Ciprofloxacin resistance per age group" #' ) #' } #' } age_groups <- function(x, split_at = c(12, 25, 55, 75), na.rm = FALSE) { meet_criteria(x, allow_class = c("numeric", "integer"), is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(split_at, allow_class = c("numeric", "integer", "character"), is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(na.rm, allow_class = "logical", has_length = 1) if (any(x < 0, na.rm = TRUE)) { x[x < 0] <- NA warning_("in `age_groups()`: NAs introduced for ages below 0.") } if (is.character(split_at)) { split_at <- split_at[1L] if (split_at %like% "^(child|kid|junior)") { split_at <- c(0, 1, 2, 4, 6, 13, 18) } else if (split_at %like% "^(elder|senior)") { split_at <- c(65, 75, 85) } else if (split_at %like% "^five") { split_at <- 1:20 * 5 } else if (split_at %like% "^ten") { split_at <- 1:10 * 10 } } split_at <- sort(unique(as.integer(split_at))) if (!split_at[1] == 0) { # add base number 0 split_at <- c(0, split_at) } split_at <- split_at[!is.na(split_at)] stop_if(length(split_at) == 1, "invalid value for `split_at`") # only 0 is available # turn input values to 'split_at' indices y <- x lbls <- split_at for (i in seq_len(length(split_at))) { y[x >= split_at[i]] <- i # create labels lbls[i - 1] <- paste0(unique(c(split_at[i - 1], split_at[i] - 1)), collapse = "-") } # last category lbls[length(lbls)] <- paste0(split_at[length(split_at)], "+") agegroups <- factor(lbls[y], levels = lbls, ordered = TRUE) if (isTRUE(na.rm)) { agegroups <- agegroups[!is.na(agegroups)] } agegroups }
/scratch/gouwar.j/cran-all/cranData/AMR/R/age.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Generate Antibiogram: Traditional, Combined, Syndromic, or Weighted-Incidence Syndromic Combination (WISCA) #' #' Generate an antibiogram, and communicate the results in plots or tables. These functions follow the logic of Klinker *et al.* and Barbieri *et al.* (see *Source*), and allow reporting in e.g. R Markdown and Quarto as well. #' @param x a [data.frame] containing at least a column with microorganisms and columns with antibiotic results (class 'sir', see [as.sir()]) #' @param antibiotics vector of any antibiotic name or code (will be evaluated with [as.ab()], column name of `x`, or (any combinations of) [antibiotic selectors][antibiotic_class_selectors] such as [aminoglycosides()] or [carbapenems()]. For combination antibiograms, this can also be set to values separated with `"+"`, such as "TZP+TOB" or "cipro + genta", given that columns resembling such antibiotics exist in `x`. See *Examples*. #' @param mo_transform a character to transform microorganism input - must be "name", "shortname", "gramstain", or one of the column names of the [microorganisms] data set: `r vector_or(colnames(microorganisms), sort = FALSE, quotes = TRUE)`. Can also be `NULL` to not transform the input. #' @param ab_transform a character to transform antibiotic input - must be one of the column names of the [antibiotics] data set: `r vector_or(colnames(antibiotics), sort = FALSE, quotes = TRUE)`. Can also be `NULL` to not transform the input. #' @param syndromic_group a column name of `x`, or values calculated to split rows of `x`, e.g. by using [ifelse()] or [`case_when()`][dplyr::case_when()]. See *Examples*. #' @param add_total_n a [logical] to indicate whether total available numbers per pathogen should be added to the table (default is `TRUE`). This will add the lowest and highest number of available isolate per antibiotic (e.g, if for *E. coli* 200 isolates are available for ciprofloxacin and 150 for amoxicillin, the returned number will be "150-200"). #' @param only_all_tested (for combination antibiograms): a [logical] to indicate that isolates must be tested for all antibiotics, see *Details* #' @param digits number of digits to use for rounding #' @param col_mo column name of the names or codes of the microorganisms (see [as.mo()]) - the default is the first column of class [`mo`]. Values will be coerced using [as.mo()]. #' @param language language to translate text, which defaults to the system language (see [get_AMR_locale()]) #' @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 combine_SI a [logical] to indicate whether all susceptibility should be determined by results of either S or I, instead of only S (default is `TRUE`) #' @param sep a separating character for antibiotic columns in combination antibiograms #' @param info a [logical] to indicate info should be printed - the default is `TRUE` only in interactive mode #' @param object an [antibiogram()] object #' @param ... when used in [R Markdown or Quarto][knitr::kable()]: arguments passed on to [knitr::kable()] (otherwise, has no use) #' @details This function returns a table with values between 0 and 100 for *susceptibility*, not resistance. #' #' **Remember that you should filter your data to let it contain only first isolates!** This is needed to exclude duplicates and to reduce selection bias. Use [first_isolate()] to determine them in your data set with one of the four available algorithms. #' #' All types of antibiograms as listed below can be plotted (using [ggplot2::autoplot()] or base \R [plot()]/[barplot()]). The `antibiogram` object can also be used directly in R Markdown / Quarto (i.e., `knitr`) for reports. In this case, [knitr::kable()] will be applied automatically and microorganism names will even be printed in italics at default (see argument `italicise`). You can also use functions from specific 'table reporting' packages to transform the output of [antibiogram()] to your needs, e.g. with `flextable::as_flextable()` or `gt::gt()`. #' #' ### Antibiogram Types #' #' There are four antibiogram types, as proposed by Klinker *et al.* (2021, \doi{10.1177/20499361211011373}), and they are all supported by [antibiogram()]: #' #' 1. **Traditional Antibiogram** #' #' Case example: Susceptibility of *Pseudomonas aeruginosa* to piperacillin/tazobactam (TZP) #' #' Code example: #' #' ```r #' antibiogram(your_data, #' antibiotics = "TZP") #' ``` #' #' 2. **Combination Antibiogram** #' #' Case example: Additional susceptibility of *Pseudomonas aeruginosa* to TZP + tobramycin versus TZP alone #' #' Code example: #' #' ```r #' antibiogram(your_data, #' antibiotics = c("TZP", "TZP+TOB", "TZP+GEN")) #' ``` #' #' 3. **Syndromic Antibiogram** #' #' Case example: Susceptibility of *Pseudomonas aeruginosa* to TZP among respiratory specimens (obtained among ICU patients only) #' #' Code example: #' #' ```r #' antibiogram(your_data, #' antibiotics = penicillins(), #' syndromic_group = "ward") #' ``` #' #' 4. **Weighted-Incidence Syndromic Combination Antibiogram (WISCA)** #' #' Case example: Susceptibility of *Pseudomonas aeruginosa* to TZP among respiratory specimens (obtained among ICU patients only) for male patients age >=65 years with heart failure #' #' Code example: #' #' ```r #' library(dplyr) #' your_data %>% #' filter(ward == "ICU" & specimen_type == "Respiratory") %>% #' antibiogram(antibiotics = c("TZP", "TZP+TOB", "TZP+GEN"), #' syndromic_group = ifelse(.$age >= 65 & #' .$gender == "Male" & #' .$condition == "Heart Disease", #' "Study Group", "Control Group")) #' ``` #' #' 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 antibiotics, 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 include as include as include as include as #' numerator denominator numerator denominator #' -------- -------- ---------- ----------- ---------- ----------- #' 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> - - - - #' -------------------------------------------------------------------- #' ``` #' #' @source #' * Klinker KP *et al.* (2021). **Antimicrobial stewardship and antibiograms: importance of moving beyond traditional antibiograms**. *Therapeutic Advances in Infectious Disease*, May 5;8:20499361211011373; \doi{10.1177/20499361211011373} #' * Barbieri E *et al.* (2021). **Development of a Weighted-Incidence Syndromic Combination Antibiogram (WISCA) to guide the choice of the empiric antibiotic treatment for urinary tract infection in paediatric patients: a Bayesian approach** *Antimicrobial Resistance & Infection Control* May 1;10(1):74; \doi{10.1186/s13756-021-00939-2} #' * **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/>. #' @rdname antibiogram #' @name antibiogram #' @export #' @examples #' # example_isolates is a data set available in the AMR package. #' # run ?example_isolates for more info. #' example_isolates #' #' \donttest{ #' # Traditional antibiogram ---------------------------------------------- #' #' antibiogram(example_isolates, #' antibiotics = c(aminoglycosides(), carbapenems()) #' ) #' #' antibiogram(example_isolates, #' antibiotics = aminoglycosides(), #' ab_transform = "atc", #' mo_transform = "gramstain" #' ) #' #' antibiogram(example_isolates, #' antibiotics = carbapenems(), #' ab_transform = "name", #' mo_transform = "name" #' ) #' #' #' # Combined antibiogram ------------------------------------------------- #' #' # combined antibiotics yield higher empiric coverage #' antibiogram(example_isolates, #' antibiotics = c("TZP", "TZP+TOB", "TZP+GEN"), #' mo_transform = "gramstain" #' ) #' #' # names of antibiotics do not need to resemble columns exactly: #' antibiogram(example_isolates, #' antibiotics = c("Cipro", "cipro + genta"), #' mo_transform = "gramstain", #' ab_transform = "name", #' sep = " & " #' ) #' #' #' # Syndromic antibiogram ------------------------------------------------ #' #' # the data set could contain a filter for e.g. respiratory specimens #' antibiogram(example_isolates, #' antibiotics = c(aminoglycosides(), carbapenems()), #' syndromic_group = "ward" #' ) #' #' # now define a data set with only E. coli #' ex1 <- example_isolates[which(mo_genus() == "Escherichia"), ] #' #' # with a custom language, though this will be determined automatically #' # (i.e., this table will be in Spanish on Spanish systems) #' antibiogram(ex1, #' antibiotics = aminoglycosides(), #' ab_transform = "name", #' syndromic_group = ifelse(ex1$ward == "ICU", #' "UCI", "No UCI" #' ), #' language = "es" #' ) #' #' #' # Weighted-incidence syndromic combination antibiogram (WISCA) --------- #' #' # the data set could contain a filter for e.g. respiratory specimens/ICU #' antibiogram(example_isolates, #' antibiotics = c("AMC", "AMC+CIP", "TZP", "TZP+TOB"), #' mo_transform = "gramstain", #' minimum = 10, # this should be >=30, but now just as example #' syndromic_group = ifelse(example_isolates$age >= 65 & #' example_isolates$gender == "M", #' "WISCA Group 1", "WISCA Group 2" #' ) #' ) #' #' #' # Print the output for R Markdown / Quarto ----------------------------- #' #' ureido <- antibiogram(example_isolates, #' antibiotics = ureidopenicillins(), #' ab_transform = "name" #' ) #' #' # in an Rmd file, you would just need to return `ureido` in a chunk, #' # but to be explicit here: #' if (requireNamespace("knitr")) { #' cat(knitr::knit_print(ureido)) #' } #' #' #' # Generate plots with ggplot2 or base R -------------------------------- #' #' ab1 <- antibiogram(example_isolates, #' antibiotics = c("AMC", "CIP", "TZP", "TZP+TOB"), #' mo_transform = "gramstain" #' ) #' ab2 <- antibiogram(example_isolates, #' antibiotics = c("AMC", "CIP", "TZP", "TZP+TOB"), #' mo_transform = "gramstain", #' syndromic_group = "ward" #' ) #' #' if (requireNamespace("ggplot2")) { #' ggplot2::autoplot(ab1) #' } #' if (requireNamespace("ggplot2")) { #' ggplot2::autoplot(ab2) #' } #' #' plot(ab1) #' plot(ab2) #' } antibiogram <- function(x, antibiotics = where(is.sir), mo_transform = "shortname", ab_transform = NULL, syndromic_group = NULL, add_total_n = TRUE, only_all_tested = FALSE, digits = 0, col_mo = NULL, language = get_AMR_locale(), minimum = 30, combine_SI = TRUE, sep = " + ", info = interactive()) { meet_criteria(x, allow_class = "data.frame", contains_column_class = c("sir", "rsi")) meet_criteria(mo_transform, allow_class = "character", has_length = 1, is_in = c("name", "shortname", "gramstain", colnames(AMR::microorganisms)), allow_NULL = TRUE) meet_criteria(ab_transform, allow_class = "character", has_length = 1, is_in = colnames(AMR::antibiotics), allow_NULL = TRUE) meet_criteria(syndromic_group, allow_class = "character", allow_NULL = TRUE, allow_NA = TRUE) meet_criteria(add_total_n, allow_class = "logical", has_length = 1) meet_criteria(only_all_tested, allow_class = "logical", has_length = 1) meet_criteria(digits, allow_class = c("numeric", "integer"), has_length = 1, is_finite = TRUE) meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) language <- validate_language(language) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(sep, allow_class = "character", has_length = 1) meet_criteria(info, allow_class = "logical", has_length = 1) # try to find columns based on type if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = interactive()) stop_if(is.null(col_mo), "`col_mo` must be set") } # transform MOs x$`.mo` <- x[, col_mo, drop = TRUE] if (is.null(mo_transform)) { # leave as is } else if (mo_transform == "gramstain") { x$`.mo` <- mo_gramstain(x$`.mo`, language = language) } else if (mo_transform == "shortname") { x$`.mo` <- mo_shortname(x$`.mo`, language = language) } else if (mo_transform == "name") { x$`.mo` <- mo_name(x$`.mo`, language = language) } else { x$`.mo` <- mo_property(x$`.mo`, language = language) } x$`.mo`[is.na(x$`.mo`)] <- "(??)" # get syndromic groups if (!is.null(syndromic_group)) { if (length(syndromic_group) == 1 && syndromic_group %in% colnames(x)) { x$`.syndromic_group` <- x[, syndromic_group, drop = TRUE] } else if (!is.null(syndromic_group)) { x$`.syndromic_group` <- syndromic_group } x$`.syndromic_group`[is.na(x$`.syndromic_group`) | x$`.syndromic_group` == ""] <- paste0("(", translate_AMR("unknown", language = language), ")") has_syndromic_group <- TRUE } else { has_syndromic_group <- FALSE } # get antibiotics if (tryCatch(is.character(antibiotics), error = function(e) FALSE)) { antibiotics.bak <- antibiotics # split antibiotics on separator and make it a list antibiotics <- strsplit(gsub(" ", "", antibiotics), "+", fixed = TRUE) # get available antibiotics in data set df_ab <- get_column_abx(x, verbose = FALSE, info = FALSE) # get antibiotics from user user_ab <- suppressMessages(suppressWarnings(lapply(antibiotics, as.ab, flag_multiple_results = FALSE, info = FALSE))) non_existing <- character(0) user_ab <- lapply(user_ab, function(x) { out <- unname(df_ab[match(x, names(df_ab))]) non_existing <<- c(non_existing, x[is.na(out) & !is.na(x)]) # remove non-existing columns out[!is.na(out)] }) user_ab <- user_ab[unlist(lapply(user_ab, length)) > 0] if (length(non_existing) > 0) { warning_("The following antibiotics were not available and ignored: ", vector_and(ab_name(non_existing, language = NULL, tolower = TRUE), quotes = FALSE)) } # make list unique antibiotics <- unique(user_ab) # go through list to set AMR in combinations for (i in seq_len(length(antibiotics))) { abx <- antibiotics[[i]] for (ab in abx) { # make sure they are SIR columns x[, ab] <- as.sir(x[, ab, drop = TRUE]) } new_colname <- paste0(trimws(abx), collapse = sep) if (length(abx) == 1) { next } else { # determine whether this new column should contain S, I, R, or NA if (isTRUE(combine_SI)) { S_values <- c("S", "I") } else { S_values <- "S" } other_values <- setdiff(c("S", "I", "R"), 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 )) } } antibiotics[[i]] <- new_colname } antibiotics <- unlist(antibiotics) } else { antibiotics <- colnames(suppressWarnings(x[, antibiotics, drop = FALSE])) } if (isTRUE(has_syndromic_group)) { out <- x %pm>% pm_select(.syndromic_group, .mo, antibiotics) %pm>% pm_group_by(.syndromic_group) } else { out <- x %pm>% pm_select(.mo, antibiotics) } # get numbers of S, I, R (per group) out <- out %pm>% bug_drug_combinations( col_mo = ".mo", FUN = function(x) x ) counts <- out if (isTRUE(combine_SI)) { out$numerator <- out$S + out$I } else { out$numerator <- out$S } if (any(out$total < minimum, na.rm = TRUE)) { if (isTRUE(info)) { message_("NOTE: ", sum(out$total < minimum, na.rm = TRUE), " combinations had less than `minimum = ", minimum, "` results and were ignored", add_fn = font_red) } out <- out %pm>% subset(total >= minimum) } # regroup for summarising if (isTRUE(has_syndromic_group)) { colnames(out)[1] <- "syndromic_group" out <- out %pm>% pm_group_by(syndromic_group, mo, ab) } else { out <- out %pm>% pm_group_by(mo, ab) } out <- out %pm>% pm_summarise(SI = numerator / total) # transform names of antibiotics ab_naming_function <- function(x, t, l, s) { x <- strsplit(x, s, fixed = TRUE) out <- character(length = length(x)) for (i in seq_len(length(x))) { a <- x[[i]] if (is.null(t)) { # leave as is } else if (t == "atc") { a <- ab_atc(a, only_first = TRUE, language = l) } else { a <- ab_property(a, property = t, language = l) } if (length(a) > 1) { a <- paste0(trimws(a), collapse = sep) } out[i] <- a } out } out$ab <- ab_naming_function(out$ab, t = ab_transform, l = language, s = sep) # transform long to wide long_to_wide <- function(object, digs) { object$SI <- round(object$SI * 100, digits = digs) object <- object %pm>% # an unclassed data.frame is required for stats::reshape() as.data.frame(stringsAsFactors = FALSE) %pm>% stats::reshape(direction = "wide", idvar = "mo", timevar = "ab", v.names = "SI") colnames(object) <- gsub("^SI?[.]", "", colnames(object)) return(object) } # ungroup for long -> wide transformation attr(out, "pm_groups") <- NULL attr(out, "groups") <- NULL class(out) <- class(out)[!class(out) %in% c("grouped_df", "grouped_data")] long <- out if (isTRUE(has_syndromic_group)) { grps <- unique(out$syndromic_group) for (i in seq_len(length(grps))) { grp <- grps[i] if (i == 1) { new_df <- long_to_wide(out[which(out$syndromic_group == grp), , drop = FALSE], digs = digits) } else { new_df <- rbind_AMR( new_df, long_to_wide(out[which(out$syndromic_group == grp), , drop = FALSE], digs = digits) ) } } # sort rows new_df <- new_df %pm>% pm_arrange(mo, syndromic_group) # sort columns new_df <- new_df[, c("syndromic_group", "mo", sort(colnames(new_df)[!colnames(new_df) %in% c("syndromic_group", "mo")])), drop = FALSE] colnames(new_df)[1:2] <- translate_AMR(c("Syndromic Group", "Pathogen"), language = language) } else { new_df <- long_to_wide(out, digs = digits) # sort rows new_df <- new_df %pm>% pm_arrange(mo) # sort columns new_df <- new_df[, c("mo", sort(colnames(new_df)[colnames(new_df) != "mo"])), drop = FALSE] colnames(new_df)[1] <- translate_AMR("Pathogen", language = language) } # add total N if indicated if (isTRUE(add_total_n)) { if (isTRUE(has_syndromic_group)) { n_per_mo <- counts %pm>% pm_group_by(mo, .syndromic_group) %pm>% pm_summarise(paste0(min(total, na.rm = TRUE), "-", max(total, na.rm = TRUE))) colnames(n_per_mo) <- c("mo", "syn", "count") count_group <- n_per_mo$count[match(paste(new_df[[2]], new_df[[1]]), paste(n_per_mo$mo, n_per_mo$syn))] edit_col <- 2 } else { n_per_mo <- counts %pm>% pm_group_by(mo) %pm>% pm_summarise(paste0(min(total, na.rm = TRUE), "-", max(total, na.rm = TRUE))) colnames(n_per_mo) <- c("mo", "count") count_group <- n_per_mo$count[match(new_df[[1]], n_per_mo$mo)] edit_col <- 1 } if (NCOL(new_df) == edit_col + 1) { # only 1 antibiotic new_df[[edit_col]] <- paste0(new_df[[edit_col]], " (", unlist(lapply(strsplit(x = count_group, split = "-", fixed = TRUE), function(x) x[1])), ")") colnames(new_df)[edit_col] <- paste(colnames(new_df)[edit_col], "(N)") } else { # more than 1 antibiotic new_df[[edit_col]] <- paste0(new_df[[edit_col]], " (", count_group, ")") colnames(new_df)[edit_col] <- paste(colnames(new_df)[edit_col], "(N min-max)") } } out <- as_original_data_class(new_df, class(x), extra_class = "antibiogram") rownames(out) <- NULL structure(out, has_syndromic_group = has_syndromic_group, long = long, combine_SI = combine_SI ) } #' @export #' @rdname antibiogram plot.antibiogram <- function(x, ...) { df <- attributes(x)$long if ("syndromic_group" %in% colnames(df)) { # barplot in base R does not support facets - paste columns together df$mo <- paste(df$mo, "-", df$syndromic_group) df$syndromic_group <- NULL df <- df[order(df$mo), , drop = FALSE] } mo_levels <- unique(df$mo) mfrow_old <- graphics::par()$mfrow sqrt_levels <- sqrt(length(mo_levels)) graphics::par(mfrow = c(ceiling(sqrt_levels), floor(sqrt_levels))) for (i in seq_along(mo_levels)) { mo <- mo_levels[i] df_sub <- df[df$mo == mo, , drop = FALSE] barplot( height = df_sub$SI * 100, xlab = NULL, ylab = ifelse(isTRUE(attributes(x)$combine_SI), "%SI", "%S"), names.arg = df_sub$ab, col = "#aaaaaa", beside = TRUE, main = mo, legend = NULL ) } graphics::par(mfrow = mfrow_old) } #' @export #' @noRd barplot.antibiogram <- function(height, ...) { plot(height, ...) } #' @method autoplot antibiogram #' @rdname antibiogram # will be exported using s3_register() in R/zzz.R autoplot.antibiogram <- function(object, ...) { df <- attributes(object)$long ggplot2::ggplot(df) + ggplot2::geom_col( ggplot2::aes( x = ab, y = SI * 100, fill = if ("syndromic_group" %in% colnames(df)) { syndromic_group } else { NULL } ), position = ggplot2::position_dodge2(preserve = "single") ) + ggplot2::facet_wrap("mo") + ggplot2::labs( y = ifelse(isTRUE(attributes(object)$combine_SI), "%SI", "%S"), x = NULL, fill = if ("syndromic_group" %in% colnames(df)) { colnames(object)[1] } else { NULL } ) } # will be exported in zzz.R #' @method knit_print antibiogram #' @param italicise a [logical] to indicate whether the microorganism names in the [knitr][knitr::kable()] table should be made italic, using [italicise_taxonomy()]. #' @param na character to use for showing `NA` values #' @rdname antibiogram knit_print.antibiogram <- function(x, italicise = TRUE, na = getOption("knitr.kable.NA", default = ""), ...) { stop_ifnot_installed("knitr") meet_criteria(italicise, allow_class = "logical", has_length = 1) meet_criteria(na, allow_class = "character", has_length = 1, allow_NA = TRUE) if (isTRUE(italicise)) { # make all microorganism names italic, according to nomenclature names_col <- ifelse(isTRUE(attributes(x)$has_syndromic_group), 2, 1) x[[names_col]] <- italicise_taxonomy(x[[names_col]], type = "markdown") } old_option <- getOption("knitr.kable.NA") options(knitr.kable.NA = na) on.exit(options(knitr.kable.NA = old_option)) out <- paste(c("", "", knitr::kable(x, ..., output = FALSE)), collapse = "\n") knitr::asis_output(out) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/antibiogram.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Get ATC Properties from WHOCC Website #' #' Gets data from the WHOCC website to determine properties of an Anatomical Therapeutic Chemical (ATC) (e.g. an antibiotic), such as the name, defined daily dose (DDD) or standard unit. #' @param atc_code a [character] (vector) with ATC code(s) of antibiotics, will be coerced with [as.ab()] and [ab_atc()] internally if not a valid ATC code #' @param property property of an ATC code. Valid values are `"ATC"`, `"Name"`, `"DDD"`, `"U"` (`"unit"`), `"Adm.R"`, `"Note"` and `groups`. For this last option, all hierarchical groups of an ATC code will be returned, see *Examples*. #' @param administration type of administration when using `property = "Adm.R"`, see *Details* #' @param url url of website of the WHOCC. The sign `%s` can be used as a placeholder for ATC codes. #' @param url_vet url of website of the WHOCC for veterinary medicine. The sign `%s` can be used as a placeholder for ATC_vet codes (that all start with "Q"). #' @param ... arguments to pass on to `atc_property` #' @details #' Options for argument `administration`: #' #' - `"Implant"` = Implant #' - `"Inhal"` = Inhalation #' - `"Instill"` = Instillation #' - `"N"` = nasal #' - `"O"` = oral #' - `"P"` = parenteral #' - `"R"` = rectal #' - `"SL"` = sublingual/buccal #' - `"TD"` = transdermal #' - `"V"` = vaginal #' #' Abbreviations of return values when using `property = "U"` (unit): #' #' - `"g"` = gram #' - `"mg"` = milligram #' - `"mcg"` = microgram #' - `"U"` = unit #' - `"TU"` = thousand units #' - `"MU"` = million units #' - `"mmol"` = millimole #' - `"ml"` = millilitre (e.g. eyedrops) #' #' **N.B. This function requires an internet connection and only works if the following packages are installed: `curl`, `rvest`, `xml2`.** #' @export #' @rdname atc_online #' @source <https://www.whocc.no/atc_ddd_alterations__cumulative/ddd_alterations/abbrevations/> #' @examples #' \donttest{ #' if (requireNamespace("curl") && requireNamespace("rvest") && requireNamespace("xml2")) { #' # oral DDD (Defined Daily Dose) of amoxicillin #' atc_online_property("J01CA04", "DDD", "O") #' atc_online_ddd(ab_atc("amox")) #' #' # parenteral DDD (Defined Daily Dose) of amoxicillin #' atc_online_property("J01CA04", "DDD", "P") #' #' atc_online_property("J01CA04", property = "groups") # search hierarchical groups of amoxicillin #' } #' } atc_online_property <- function(atc_code, property, administration = "O", url = "https://www.whocc.no/atc_ddd_index/?code=%s&showdescription=no", url_vet = "https://www.whocc.no/atcvet/atcvet_index/?code=%s&showdescription=no") { meet_criteria(atc_code, allow_class = "character") meet_criteria(property, allow_class = "character", has_length = 1, is_in = c("ATC", "Name", "DDD", "U", "unit", "Adm.R", "Note", "groups"), ignore.case = TRUE) meet_criteria(administration, allow_class = "character", has_length = 1) meet_criteria(url, allow_class = "character", has_length = 1, looks_like = "https?://") meet_criteria(url_vet, allow_class = "character", has_length = 1, looks_like = "https?://") has_internet <- import_fn("has_internet", "curl") html_attr <- import_fn("html_attr", "rvest") html_children <- import_fn("html_children", "rvest") html_node <- import_fn("html_node", "rvest") html_nodes <- import_fn("html_nodes", "rvest") html_table <- import_fn("html_table", "rvest") html_text <- import_fn("html_text", "rvest") read_html <- import_fn("read_html", "xml2") if (!all(atc_code %in% unlist(AMR::antibiotics$atc))) { atc_code <- as.character(ab_atc(atc_code, only_first = TRUE)) } if (!has_internet()) { message_("There appears to be no internet connection, returning NA.", add_fn = font_red, as_note = FALSE ) return(rep(NA, length(atc_code))) } property <- tolower(property) # also allow unit as property if (property == "unit") { property <- "u" } if (property == "ddd") { returnvalue <- rep(NA_real_, length(atc_code)) } else if (property == "groups") { returnvalue <- list() } else { returnvalue <- rep(NA_character_, length(atc_code)) } progress <- progress_ticker(n = length(atc_code), 3) on.exit(close(progress)) for (i in seq_len(length(atc_code))) { progress$tick() if (atc_code[i] %like% "^Q") { # veterinary drugs, ATC_vet codes start with a "Q" atc_url <- url_vet } else { atc_url <- url } atc_url <- sub("%s", atc_code[i], atc_url, fixed = TRUE) if (property == "groups") { out <- tryCatch( read_html(atc_url) %pm>% html_node("#content") %pm>% html_children() %pm>% html_node("a"), error = function(e) NULL ) if (is.null(out)) { message_("Connection to ", atc_url, " failed.") return(rep(NA, length(atc_code))) } # get URLS of items hrefs <- out %pm>% html_attr("href") # get text of items texts <- out %pm>% html_text() # select only text items where URL like "code=" texts <- texts[grepl("?code=", tolower(hrefs), fixed = TRUE)] # last one is antibiotics, skip it texts <- texts[seq_len(length(texts)) - 1] returnvalue <- c(list(texts), returnvalue) } else { out <- tryCatch( read_html(atc_url) %pm>% html_nodes("table") %pm>% html_table(header = TRUE) %pm>% as.data.frame(stringsAsFactors = FALSE), error = function(e) NULL ) if (is.null(out)) { message_("Connection to ", atc_url, " failed.") return(rep(NA, length(atc_code))) } # case insensitive column names colnames(out) <- gsub("^atc.*", "atc", tolower(colnames(out))) if (length(out) == 0) { warning_("in `atc_online_property()`: ATC not found: ", atc_code[i], ". Please check ", atc_url, ".") returnvalue[i] <- NA next } if (property %in% c("atc", "name")) { # ATC and name are only in first row returnvalue[i] <- out[1, property, drop = TRUE] } else { if (!"adm.r" %in% colnames(out) || is.na(out[1, "adm.r", drop = TRUE])) { returnvalue[i] <- NA next } else { for (j in seq_len(nrow(out))) { if (out[j, "adm.r"] == administration) { returnvalue[i] <- out[j, property, drop = TRUE] } } } } } } if (property == "groups" && length(returnvalue) == 1) { returnvalue <- returnvalue[[1]] } returnvalue } #' @rdname atc_online #' @export atc_online_groups <- function(atc_code, ...) { meet_criteria(atc_code, allow_class = "character") atc_online_property(atc_code = atc_code, property = "groups", ...) } #' @rdname atc_online #' @export atc_online_ddd <- function(atc_code, ...) { meet_criteria(atc_code, allow_class = "character") atc_online_property(atc_code = atc_code, property = "ddd", ...) } #' @rdname atc_online #' @export atc_online_ddd_units <- function(atc_code, ...) { meet_criteria(atc_code, allow_class = "character") atc_online_property(atc_code = atc_code, property = "unit", ...) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/atc_online.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Transform Input to an Antiviral Drug ID #' #' Use this function to determine the antiviral drug code of one or more antiviral drugs. The data set [antivirals] will be searched for abbreviations, official names and synonyms (brand names). #' @param x a [character] vector to determine to antiviral drug ID #' @param flag_multiple_results a [logical] to indicate whether a note should be printed to the console that probably more than one antiviral drug code or name can be retrieved from a single input value. #' @param info a [logical] to indicate whether a progress bar should be printed - the default is `TRUE` only in interactive mode #' @param ... arguments passed on to internal functions #' @rdname as.av #' @inheritSection WHOCC WHOCC #' @details All entries in the [antivirals] data set have three different identifiers: a human readable EARS-Net code (column `ab`, used by ECDC and WHONET), an ATC code (column `atc`, used by WHO), and a CID code (column `cid`, Compound ID, used by PubChem). The data set contains more than 5,000 official brand names from many different countries, as found in PubChem. Not that some drugs contain multiple ATC codes. #' #' All these properties will be searched for the user input. The [as.av()] can correct for different forms of misspelling: #' #' * Wrong spelling of drug names (such as "acyclovir"), which corrects for most audible similarities such as f/ph, x/ks, c/z/s, t/th, etc. #' * Too few or too many vowels or consonants #' * Switching two characters (such as "aycclovir", often the case in clinical data, when doctors typed too fast) #' * Digitalised paper records, leaving artefacts like 0/o/O (zero and O's), B/8, n/r, etc. #' #' Use the [`av_*`][av_property()] functions to get properties based on the returned antiviral drug ID, see *Examples*. #' #' Note: the [as.av()] and [`av_*`][av_property()] functions may use very long regular expression to match brand names of antimicrobial drugs. This may fail on some systems. #' @section Source: #' World Health Organization (WHO) Collaborating Centre for Drug Statistics Methodology: \url{https://www.whocc.no/atc_ddd_index/} #' #' European Commission Public Health PHARMACEUTICALS - COMMUNITY REGISTER: \url{https://ec.europa.eu/health/documents/community-register/html/reg_hum_atc.htm} #' @aliases av #' @return A [character] [vector] with additional class [`ab`] #' @seealso #' * [antivirals] for the [data.frame] that is being used to determine ATCs #' * [av_from_text()] for a function to retrieve antimicrobial drugs from clinical text (from health care records) #' @inheritSection AMR Reference Data Publicly Available #' @export #' @examples #' # these examples all return "ACI", the ID of aciclovir: #' as.av("J05AB01") #' as.av("J 05 AB 01") #' as.av("Aciclovir") #' as.av("aciclo") #' as.av(" aciclo 123") #' as.av("ACICL") #' as.av("ACI") #' as.av("Virorax") # trade name #' as.av("Zovirax") # trade name #' #' as.av("acyklofir") # severe spelling error, yet works #' #' # use av_* functions to get a specific properties (see ?av_property); #' # they use as.av() internally: #' av_name("J05AB01") #' av_name("acicl") as.av <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) { meet_criteria(x, allow_class = c("character", "numeric", "integer", "factor"), allow_NA = TRUE) meet_criteria(flag_multiple_results, allow_class = "logical", has_length = 1) meet_criteria(info, allow_class = "logical", has_length = 1) if (is.av(x)) { return(x) } if (all(x %in% c(AMR_env$AV_lookup$av, NA))) { # all valid AB codes, but not yet right class return(set_clean_class(x, new_class = c("av", "character") )) } initial_search <- is.null(list(...)$initial_search) already_regex <- isTRUE(list(...)$already_regex) fast_mode <- isTRUE(list(...)$fast_mode) x_bak <- x x <- toupper(x) # remove diacritics x <- iconv(x, from = "UTF-8", to = "ASCII//TRANSLIT") x <- gsub('"', "", x, fixed = TRUE) x <- gsub("(specimen|specimen date|specimen_date|spec_date|gender|^dates?$)", "", x, ignore.case = TRUE, perl = TRUE) x_bak_clean <- x if (already_regex == FALSE) { x_bak_clean <- generalise_antibiotic_name(x_bak_clean) } x <- unique(x_bak_clean) # this means that every x is in fact generalise_antibiotic_name(x) x_new <- rep(NA_character_, length(x)) x_unknown <- character(0) x_unknown_ATCs <- character(0) note_if_more_than_one_found <- function(found, index, from_text) { if (isTRUE(initial_search) && isTRUE(length(from_text) > 1)) { avnames <- av_name(from_text, tolower = TRUE, initial_search = FALSE) if (av_name(found[1L], language = NULL) %like% "(clavulanic acid|avibactam)") { avnames <- avnames[!avnames %in% c("clavulanic acid", "avibactam")] } if (length(avnames) > 1) { warning_( "More than one result was found for item ", index, ": ", vector_and(avnames, quotes = FALSE) ) } } found[1L] } # Fill in names, AB codes, CID codes and ATC codes directly (`x` is already clean and uppercase) known_names <- x %in% AMR_env$AV_lookup$generalised_name x_new[known_names] <- AMR_env$AV_lookup$av[match(x[known_names], AMR_env$AV_lookup$generalised_name)] known_codes_av <- x %in% AMR_env$AV_lookup$av known_codes_atc <- vapply(FUN.VALUE = logical(1), x, function(x_) x_ %in% unlist(AMR_env$AV_lookup$atc), USE.NAMES = FALSE) known_codes_cid <- x %in% AMR_env$AV_lookup$cid x_new[known_codes_av] <- AMR_env$AV_lookup$av[match(x[known_codes_av], AMR_env$AV_lookup$av)] x_new[known_codes_atc] <- AMR_env$AV_lookup$av[vapply( FUN.VALUE = integer(1), x[known_codes_atc], function(x_) { which(vapply( FUN.VALUE = logical(1), AMR_env$AV_lookup$atc, function(atc) x_ %in% atc ))[1L] }, USE.NAMES = FALSE )] x_new[known_codes_cid] <- AMR_env$AV_lookup$av[match(x[known_codes_cid], AMR_env$AV_lookup$cid)] previously_coerced <- x %in% AMR_env$av_previously_coerced$x x_new[previously_coerced & is.na(x_new)] <- AMR_env$av_previously_coerced$av[match(x[is.na(x_new) & x %in% AMR_env$av_previously_coerced$x], AMR_env$av_previously_coerced$x)] already_known <- known_names | known_codes_av | known_codes_atc | known_codes_cid | previously_coerced # fix for NAs x_new[is.na(x)] <- NA already_known[is.na(x)] <- FALSE if (isTRUE(initial_search) && sum(already_known) < length(x)) { progress <- progress_ticker(n = sum(!already_known), n_min = 25, print = info) # start if n >= 25 on.exit(close(progress)) } for (i in which(!already_known)) { if (isTRUE(initial_search)) { progress$tick() } if (is.na(x[i]) || is.null(x[i])) { next } if (identical(x[i], "") || # prevent "bacteria" from coercing to TMP, since Bacterial is a brand name of it: identical(tolower(x[i]), "bacteria")) { x_unknown <- c(x_unknown, x_bak[x[i] == x_bak_clean][1]) next } if (x[i] %like_case% "[A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9]") { # seems an ATC code, but the available ones are in `already_known`, so: x_unknown <- c(x_unknown, x[i]) x_unknown_ATCs <- c(x_unknown_ATCs, x[i]) x_new[i] <- NA_character_ next } if (fast_mode == FALSE && flag_multiple_results == TRUE && x[i] %like% "[ ]") { from_text <- tryCatch(suppressWarnings(av_from_text(x[i], initial_search = FALSE, translate_av = FALSE)[[1]]), error = function(e) character(0) ) } else { from_text <- character(0) } # old code for phenoxymethylpenicillin (Peni V) if (x[i] == "PNV") { x_new[i] <- "PHN" next } # exact LOINC code loinc_found <- unlist(lapply( AMR_env$AV_lookup$generalised_loinc, function(s) x[i] %in% s )) found <- AMR_env$AV_lookup$av[loinc_found == TRUE] if (length(found) > 0) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # exact synonym synonym_found <- unlist(lapply( AMR_env$AV_lookup$generalised_synonyms, function(s) x[i] %in% s )) found <- AMR_env$AV_lookup$av[synonym_found == TRUE] if (length(found) > 0) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # length of input is quite long, and Levenshtein distance is only max 2 if (nchar(x[i]) >= 10) { levenshtein <- as.double(utils::adist(x[i], AMR_env$AV_lookup$generalised_name)) if (any(levenshtein <= 2)) { found <- AMR_env$AV_lookup$av[which(levenshtein <= 2)] x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } } # allow characters that resemble others, but only continue when having more than 3 characters if (nchar(x[i]) <= 3) { x_unknown <- c(x_unknown, x_bak[x[i] == x_bak_clean][1]) next } x_spelling <- x[i] if (already_regex == FALSE) { x_spelling <- gsub("[IY]+", "[IY]+", x_spelling, perl = TRUE) x_spelling <- gsub("(C|K|Q|QU|S|Z|X|KS)+", "(C|K|Q|QU|S|Z|X|KS)+", x_spelling, perl = TRUE) x_spelling <- gsub("(PH|F|V)+", "(PH|F|V)+", x_spelling, perl = TRUE) x_spelling <- gsub("(TH|T)+", "(TH|T)+", x_spelling, perl = TRUE) x_spelling <- gsub("A+", "A+", x_spelling, perl = TRUE) x_spelling <- gsub("E+", "E+", x_spelling, perl = TRUE) x_spelling <- gsub("O+", "O+", x_spelling, perl = TRUE) # allow any ending of -in/-ine and -im/-ime x_spelling <- gsub("(\\[IY\\]\\+(N|M)|\\[IY\\]\\+(N|M)E\\+?)$", "[IY]+(N|M)E*", x_spelling, perl = TRUE) # allow any ending of -ol/-ole x_spelling <- gsub("(O\\+L|O\\+LE\\+)$", "O+LE*", x_spelling, perl = TRUE) # allow any ending of -on/-one x_spelling <- gsub("(O\\+N|O\\+NE\\+)$", "O+NE*", x_spelling, perl = TRUE) # replace multiple same characters to single one with '+', like "ll" -> "l+" x_spelling <- gsub("(.)\\1+", "\\1+", x_spelling, perl = TRUE) # replace spaces and slashes with a possibility on both x_spelling <- gsub("[ /]", "( .*|.*/)", x_spelling, perl = TRUE) # correct for digital reading text (OCR) x_spelling <- gsub("[NRD8B]", "[NRD8B]", x_spelling, perl = TRUE) x_spelling <- gsub("(O|0)", "(O|0)+", x_spelling, perl = TRUE) x_spelling <- gsub("++", "+", x_spelling, fixed = TRUE) } # try if name starts with it found <- AMR_env$AV_lookup[which(AMR_env$AV_lookup$generalised_name %like% paste0("^", x_spelling)), "av", drop = TRUE] if (length(found) > 0) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # try if name ends with it found <- AMR_env$AV_lookup[which(AMR_env$AV_lookup$generalised_name %like% paste0(x_spelling, "$")), "av", drop = TRUE] if (nchar(x[i]) >= 4 && length(found) > 0) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # and try if any synonym starts with it synonym_found <- unlist(lapply( AMR_env$AV_lookup$generalised_synonyms, function(s) any(s %like% paste0("^", x_spelling)) )) found <- AMR_env$AV_lookup$av[synonym_found == TRUE] if (length(found) > 0) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # INITIAL SEARCH - More uncertain results ---- if (isTRUE(initial_search) && fast_mode == FALSE) { # only run on first try # try by removing all spaces if (x[i] %like% " ") { found <- suppressWarnings(as.av(gsub(" +", "", x[i], perl = TRUE), initial_search = FALSE)) if (length(found) > 0 && !is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } } # try by removing all spaces and numbers if (x[i] %like% " " || x[i] %like% "[0-9]") { found <- suppressWarnings(as.av(gsub("[ 0-9]", "", x[i], perl = TRUE), initial_search = FALSE)) if (length(found) > 0 && !is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } } # transform back from other languages and try again x_translated <- paste( lapply( strsplit(x[i], "[^A-Z0-9]"), function(y) { for (i in seq_len(length(y))) { for (lang in LANGUAGES_SUPPORTED[LANGUAGES_SUPPORTED != "en"]) { y[i] <- ifelse(tolower(y[i]) %in% tolower(TRANSLATIONS[, lang, drop = TRUE]), TRANSLATIONS[which(tolower(TRANSLATIONS[, lang, drop = TRUE]) == tolower(y[i]) & !isFALSE(TRANSLATIONS$fixed)), "pattern"], y[i] ) } } generalise_antibiotic_name(y) } )[[1]], collapse = "/" ) x_translated_guess <- suppressWarnings(as.av(x_translated, initial_search = FALSE)) if (!is.na(x_translated_guess)) { x_new[i] <- x_translated_guess next } # now also try to coerce brandname combinations like "Amoxy/clavulanic acid" x_translated <- paste( lapply( strsplit(x_translated, "[^A-Z0-9 ]"), function(y) { for (i in seq_len(length(y))) { y_name <- suppressWarnings(av_name(y[i], language = NULL, initial_search = FALSE)) y[i] <- ifelse(!is.na(y_name), y_name, y[i] ) } generalise_antibiotic_name(y) } )[[1]], collapse = "/" ) x_translated_guess <- suppressWarnings(as.av(x_translated, initial_search = FALSE)) if (!is.na(x_translated_guess)) { x_new[i] <- x_translated_guess next } # try by removing all trailing capitals if (x[i] %like_case% "[a-z]+[A-Z]+$") { found <- suppressWarnings(as.av(gsub("[A-Z]+$", "", x[i], perl = TRUE), initial_search = FALSE)) if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } } # keep only letters found <- suppressWarnings(as.av(gsub("[^A-Z]", "", x[i], perl = TRUE), initial_search = FALSE)) if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # try from a bigger text, like from a health care record, see ?av_from_text # already calculated above if flag_multiple_results = TRUE if (flag_multiple_results == TRUE) { found <- from_text[1L] } else { found <- tryCatch(suppressWarnings(av_from_text(x[i], initial_search = FALSE, translate_av = FALSE)[[1]][1L]), error = function(e) NA_character_ ) } if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # first 5 found <- suppressWarnings(as.av(substr(x[i], 1, 5), initial_search = FALSE)) if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # make all consonants facultative search_str <- gsub("([BCDFGHJKLMNPQRSTVWXZ])", "\\1*", x[i], perl = TRUE) found <- suppressWarnings(as.av(search_str, initial_search = FALSE, already_regex = TRUE)) # keep at least 4 normal characters if (nchar(gsub(".\\*", "", search_str, perl = TRUE)) < 4) { found <- NA } if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # make all vowels facultative search_str <- gsub("([AEIOUY])", "\\1*", x[i], perl = TRUE) found <- suppressWarnings(as.av(search_str, initial_search = FALSE, already_regex = TRUE)) # keep at least 5 normal characters if (nchar(gsub(".\\*", "", search_str, perl = TRUE)) < 5) { found <- NA } if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # allow misspelling of vowels x_spelling <- gsub("A+", "[AEIOU]+", x_spelling, fixed = TRUE) x_spelling <- gsub("E+", "[AEIOU]+", x_spelling, fixed = TRUE) x_spelling <- gsub("I+", "[AEIOU]+", x_spelling, fixed = TRUE) x_spelling <- gsub("O+", "[AEIOU]+", x_spelling, fixed = TRUE) x_spelling <- gsub("U+", "[AEIOU]+", x_spelling, fixed = TRUE) found <- suppressWarnings(as.av(x_spelling, initial_search = FALSE, already_regex = TRUE)) if (!is.na(found)) { x_new[i] <- note_if_more_than_one_found(found, i, from_text) next } # try with switched character, like "mreopenem" for (j in seq_len(nchar(x[i]))) { x_switched <- paste0( # beginning part: substr(x[i], 1, j - 1), # here is the switching of 2 characters: substr(x[i], j + 1, j + 1), substr(x[i], j, j), # ending part: substr(x[i], j + 2, nchar(x[i])) ) found <- suppressWarnings(as.av(x_switched, initial_search = FALSE)) if (!is.na(found)) { break } } if (!is.na(found)) { x_new[i] <- found[1L] next } } # end of initial_search = TRUE # not found x_unknown <- c(x_unknown, x_bak[x[i] == x_bak_clean][1]) } if (isTRUE(initial_search) && sum(already_known) < length(x)) { close(progress) } # save to package env to save time for next time if (isTRUE(initial_search)) { AMR_env$av_previously_coerced <- AMR_env$av_previously_coerced[which(!AMR_env$av_previously_coerced$x %in% x), , drop = FALSE] AMR_env$av_previously_coerced <- unique(rbind_AMR( AMR_env$av_previously_coerced, data.frame( x = x, av = x_new, x_bak = x_bak[match(x, x_bak_clean)], stringsAsFactors = FALSE ) )) } # take failed ATC codes apart from rest if (length(x_unknown_ATCs) > 0 && fast_mode == FALSE) { warning_( "in `as.av()`: these ATC codes are not (yet) in the antivirals data set: ", vector_and(x_unknown_ATCs), "." ) } x_unknown <- x_unknown[!x_unknown %in% x_unknown_ATCs] x_unknown <- c( x_unknown, AMR_env$av_previously_coerced$x_bak[which(AMR_env$av_previously_coerced$x %in% x & is.na(AMR_env$av_previously_coerced$av))] ) if (length(x_unknown) > 0 && fast_mode == FALSE) { warning_( "in `as.av()`: these values could not be coerced to a valid antiviral drug ID: ", vector_and(x_unknown), "." ) } x_result <- x_new[match(x_bak_clean, x)] if (length(x_result) == 0) { x_result <- NA_character_ } set_clean_class(x_result, new_class = c("av", "character") ) } #' @rdname as.av #' @export is.av <- function(x) { inherits(x, "av") } # will be exported using s3_register() in R/zzz.R pillar_shaft.av <- function(x, ...) { out <- trimws(format(x)) out[!is.na(x)] <- gsub("+", font_subtle("+"), out[!is.na(x)], fixed = TRUE) out[is.na(x)] <- font_na(NA) create_pillar_column(out, align = "left", min_width = 4) } # will be exported using s3_register() in R/zzz.R type_sum.av <- function(x, ...) { "av" } #' @method print av #' @export #' @noRd print.av <- function(x, ...) { cat("Class 'av'\n") print(as.character(x), quote = FALSE) } #' @method as.data.frame av #' @export #' @noRd as.data.frame.av <- function(x, ...) { nm <- deparse1(substitute(x)) if (!"nm" %in% names(list(...))) { as.data.frame.vector(as.av(x), ..., nm = nm) } else { as.data.frame.vector(as.av(x), ...) } } #' @method [ av #' @export #' @noRd "[.av" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [[ av #' @export #' @noRd "[[.av" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [<- av #' @export #' @noRd "[<-.av" <- function(i, j, ..., value) { y <- NextMethod() attributes(y) <- attributes(i) return_after_integrity_check(y, "antiviral drug code", AMR_env$AV_lookup$av) } #' @method [[<- av #' @export #' @noRd "[[<-.av" <- function(i, j, ..., value) { y <- NextMethod() attributes(y) <- attributes(i) return_after_integrity_check(y, "antiviral drug code", AMR_env$AV_lookup$av) } #' @method c av #' @export #' @noRd c.av <- function(...) { x <- list(...)[[1L]] y <- NextMethod() attributes(y) <- attributes(x) return_after_integrity_check(y, "antiviral drug code", AMR_env$AV_lookup$av) } #' @method unique av #' @export #' @noRd unique.av <- function(x, incomparables = FALSE, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method rep av #' @export #' @noRd rep.av <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } get_translate_av <- function(translate_av) { translate_av <- as.character(translate_av)[1L] if (translate_av %in% c("TRUE", "official")) { return("name") } else if (translate_av %in% c(NA_character_, "FALSE")) { return(FALSE) } else { translate_av <- tolower(translate_av) stop_ifnot(translate_av %in% colnames(AMR::antivirals), "invalid value for 'translate_av', this must be a column name of the antivirals data set\n", "or TRUE (equals 'name') or FALSE to not translate at all.", call = FALSE ) translate_av } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/av.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Retrieve Antiviral Drug Names and Doses from Clinical Text #' #' Use this function on e.g. clinical texts from health care records. It returns a [list] with all antiviral drugs, doses and forms of administration found in the texts. #' @param text text to analyse #' @param type type of property to search for, either `"drug"`, `"dose"` or `"administration"`, see *Examples* #' @param collapse a [character] to pass on to `paste(, collapse = ...)` to only return one [character] per element of `text`, see *Examples* #' @param translate_av if `type = "drug"`: a column name of the [antivirals] data set to translate the antibiotic abbreviations to, using [av_property()]. The default is `FALSE`. Using `TRUE` is equal to using "name". #' @param thorough_search a [logical] to indicate whether the input must be extensively searched for misspelling and other faulty input values. Setting this to `TRUE` will take considerably more time than when using `FALSE`. At default, it will turn `TRUE` when all input elements contain a maximum of three words. #' @param info a [logical] to indicate whether a progress bar should be printed - the default is `TRUE` only in interactive mode #' @param ... arguments passed on to [as.av()] #' @details This function is also internally used by [as.av()], although it then only searches for the first drug name and will throw a note if more drug names could have been returned. Note: the [as.av()] function may use very long regular expression to match brand names of antiviral drugs. This may fail on some systems. #' #' ### Argument `type` #' At default, the function will search for antiviral drug names. All text elements will be searched for official names, ATC codes and brand names. As it uses [as.av()] internally, it will correct for misspelling. #' #' With `type = "dose"` (or similar, like "dosing", "doses"), all text elements will be searched for [numeric] values that are higher than 100 and do not resemble years. The output will be [numeric]. It supports any unit (g, mg, IE, etc.) and multiple values in one clinical text, see *Examples*. #' #' With `type = "administration"` (or abbreviations, like "admin", "adm"), all text elements will be searched for a form of drug administration. It supports the following forms (including common abbreviations): buccal, implant, inhalation, instillation, intravenous, nasal, oral, parenteral, rectal, sublingual, transdermal and vaginal. Abbreviations for oral (such as 'po', 'per os') will become "oral", all values for intravenous (such as 'iv', 'intraven') will become "iv". It supports multiple values in one clinical text, see *Examples*. #' #' ### Argument `collapse` #' Without using `collapse`, this function will return a [list]. This can be convenient to use e.g. inside a `mutate()`):\cr #' `df %>% mutate(avx = av_from_text(clinical_text))` #' #' The returned AV codes can be transformed to official names, groups, etc. with all [`av_*`][av_property()] functions such as [av_name()] and [av_group()], or by using the `translate_av` argument. #' #' With using `collapse`, this function will return a [character]:\cr #' `df %>% mutate(avx = av_from_text(clinical_text, collapse = "|"))` #' @export #' @return A [list], or a [character] if `collapse` is not `NULL` #' @examples #' av_from_text("28/03/2020 valaciclovir po tid") #' av_from_text("28/03/2020 valaciclovir po tid", type = "admin") av_from_text <- function(text, type = c("drug", "dose", "administration"), collapse = NULL, translate_av = FALSE, thorough_search = NULL, info = interactive(), ...) { if (missing(type)) { type <- type[1L] } meet_criteria(text) meet_criteria(type, allow_class = "character", has_length = 1) meet_criteria(collapse, has_length = 1, allow_NULL = TRUE) meet_criteria(translate_av, allow_NULL = FALSE) # get_translate_av() will be more informative about what's allowed meet_criteria(thorough_search, allow_class = "logical", has_length = 1, allow_NULL = TRUE) meet_criteria(info, allow_class = "logical", has_length = 1) type <- tolower(trimws2(type)) text <- tolower(as.character(text)) text_split_all <- strsplit(text, "[ ;.,:\\|]") progress <- progress_ticker(n = length(text_split_all), n_min = 5, print = info) on.exit(close(progress)) if (type %like% "(drug|ab|anti)") { translate_av <- get_translate_av(translate_av) if (isTRUE(thorough_search) || (isTRUE(is.null(thorough_search)) && max(vapply(FUN.VALUE = double(1), text_split_all, length), na.rm = TRUE) <= 3)) { text_split_all <- text_split_all[nchar(text_split_all) >= 4 & grepl("[a-z]+", text_split_all)] result <- lapply(text_split_all, function(text_split) { progress$tick() suppressWarnings( as.av(text_split, ...) ) }) } else { # no thorough search names_atc <- substr(c(AMR::antivirals$name, AMR::antivirals$atc), 1, 5) synonyms <- unlist(AMR::antivirals$synonyms) synonyms <- synonyms[nchar(synonyms) >= 4] # regular expression must not be too long, so split synonyms in two: synonyms_part1 <- synonyms[seq_len(0.5 * length(synonyms))] synonyms_part2 <- synonyms[!synonyms %in% synonyms_part1] to_regex <- function(x) { paste0( "^(", paste0(unique(gsub("[^a-z0-9]+", "", sort(tolower(x)))), collapse = "|"), ").*" ) } result <- lapply(text_split_all, function(text_split) { progress$tick() suppressWarnings( as.av( unique(c( text_split[text_split %like_case% to_regex(names_atc)], text_split[text_split %like_case% to_regex(synonyms_part1)], text_split[text_split %like_case% to_regex(synonyms_part2)] )), ... ) ) }) } close(progress) result <- lapply(result, function(out) { out <- out[!is.na(out)] if (length(out) == 0) { as.av(NA) } else { if (!isFALSE(translate_av)) { out <- av_property(out, property = translate_av, initial_search = FALSE) } out } }) } else if (type %like% "dos") { text_split_all <- strsplit(text, " ", fixed = TRUE) result <- lapply(text_split_all, function(text_split) { text_split <- text_split[text_split %like% "^[0-9]{2,}(/[0-9]+)?[a-z]*$"] # only left part of "/", like 500 in "500/125" text_split <- gsub("/.*", "", text_split) text_split <- gsub(",", ".", text_split, fixed = TRUE) # foreign system using comma as decimal sep text_split <- as.double(gsub("[^0-9.]", "", text_split)) # minimal 100 units/mg and no years that unlikely doses text_split <- text_split[text_split >= 100 & !text_split %in% c(1951:1999, 2001:2049)] if (length(text_split) > 0) { text_split } else { NA_real_ } }) } else if (type %like% "adm") { result <- lapply(text_split_all, function(text_split) { text_split <- text_split[text_split %like% "(^iv$|intraven|^po$|per os|oral|implant|inhal|instill|nasal|paren|rectal|sublingual|buccal|trans.*dermal|vaginal)"] if (length(text_split) > 0) { text_split <- gsub("(^po$|.*per os.*)", "oral", text_split) text_split <- gsub("(^iv$|.*intraven.*)", "iv", text_split) text_split } else { NA_character_ } }) } else { stop_("`type` must be either 'drug', 'dose' or 'administration'") } # collapse text if needed if (!is.null(collapse)) { result <- vapply(FUN.VALUE = character(1), result, function(x) { if (length(x) == 1 & all(is.na(x))) { NA_character_ } else { paste0(x, collapse = collapse) } }) } result }
/scratch/gouwar.j/cran-all/cranData/AMR/R/av_from_text.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Get Properties of an Antiviral Drug #' #' Use these functions to return a specific property of an antiviral drug from the [antivirals] data set. All input values will be evaluated internally with [as.av()]. #' @param x any (vector of) text that can be coerced to a valid antiviral drug code with [as.av()] #' @param tolower a [logical] to indicate whether the first [character] of every output should be transformed to a lower case [character]. #' @param property one of the column names of one of the [antivirals] data set: `vector_or(colnames(antivirals), sort = FALSE)`. #' @param language language of the returned text - the default is system language (see [get_AMR_locale()]) and can also be set with the [package option][AMR-options] [`AMR_locale`][AMR-options]. Use `language = NULL` or `language = ""` to prevent translation. #' @param administration way of administration, either `"oral"` or `"iv"` #' @param open browse the URL using [utils::browseURL()] #' @param ... other arguments passed on to [as.av()] #' @details All output [will be translated][translate] where possible. #' #' The function [av_url()] will return the direct URL to the official WHO website. A warning will be returned if the required ATC code is not available. #' @inheritSection as.av Source #' @rdname av_property #' @name av_property #' @return #' - An [integer] in case of [av_cid()] #' - A named [list] in case of [av_info()] and multiple [av_atc()]/[av_synonyms()]/[av_tradenames()] #' - A [double] in case of [av_ddd()] #' - A [character] in all other cases #' @export #' @seealso [antivirals] #' @inheritSection AMR Reference Data Publicly Available #' @examples #' # all properties: #' av_name("ACI") #' av_atc("ACI") #' av_cid("ACI") #' av_synonyms("ACI") #' av_tradenames("ACI") #' av_group("ACI") #' av_url("ACI") #' #' # lowercase transformation #' av_name(x = c("ACI", "VALA")) #' av_name(x = c("ACI", "VALA"), tolower = TRUE) #' #' # defined daily doses (DDD) #' av_ddd("ACI", "oral") #' av_ddd_units("ACI", "oral") #' av_ddd("ACI", "iv") #' av_ddd_units("ACI", "iv") #' #' av_info("ACI") # all properties as a list #' #' # all av_* functions use as.av() internally, so you can go from 'any' to 'any': #' av_atc("ACI") #' av_group("J05AB01") #' av_loinc("abacavir") #' av_name("29113-8") #' av_name(135398513) #' av_name("J05AB01") av_name <- function(x, language = get_AMR_locale(), tolower = FALSE, ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(tolower, allow_class = "logical", has_length = 1) x <- translate_into_language(av_validate(x = x, property = "name", ...), language = language, only_affect_ab_names = TRUE) if (tolower == TRUE) { # use perl to only transform the first character # as we want "polymyxin B", not "polymyxin b" x <- gsub("^([A-Z])", "\\L\\1", x, perl = TRUE) } x } #' @rdname av_property #' @export av_cid <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) av_validate(x = x, property = "cid", ...) } #' @rdname av_property #' @export av_synonyms <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) syns <- av_validate(x = x, property = "synonyms", ...) names(syns) <- x if (length(syns) == 1) { unname(unlist(syns)) } else { syns } } #' @rdname av_property #' @export av_tradenames <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) av_synonyms(x, ...) } #' @rdname av_property #' @export av_group <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) translate_into_language(av_validate(x = x, property = "atc_group", ...), language = language, only_affect_ab_names = TRUE) } #' @rdname av_property #' @export av_atc <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) # ATCs in the antivirals data set are not a list av_validate(x = x, property = "atc", ...) } #' @rdname av_property #' @export av_loinc <- function(x, ...) { meet_criteria(x, allow_NA = TRUE) loincs <- av_validate(x = x, property = "loinc", ...) names(loincs) <- x if (length(loincs) == 1) { unname(unlist(loincs)) } else { loincs } } #' @rdname av_property #' @export av_ddd <- function(x, administration = "oral", ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(administration, is_in = c("oral", "iv"), has_length = 1) x <- as.av(x, ...) ddd_prop <- paste0(administration, "_ddd") out <- av_validate(x = x, property = ddd_prop) if (any(av_name(x, language = NULL) %like% "/" & is.na(out))) { warning_( "in `av_ddd()`: DDDs of some combined products are available for different dose combinations and not (yet) part of the AMR package.", "Please refer to the WHOCC website:\n", "www.whocc.no/ddd/list_of_ddds_combined_products/" ) } out } #' @rdname av_property #' @export av_ddd_units <- function(x, administration = "oral", ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(administration, is_in = c("oral", "iv"), has_length = 1) x <- as.av(x, ...) ddd_prop <- paste0(administration, "_units") out <- av_validate(x = x, property = ddd_prop) if (any(av_name(x, language = NULL) %like% "/" & is.na(out))) { warning_( "in `av_ddd_units()`: DDDs of some combined products are available for different dose combinations and not (yet) part of the AMR package.", "Please refer to the WHOCC website:\n", "www.whocc.no/ddd/list_of_ddds_combined_products/" ) } out } #' @rdname av_property #' @export av_info <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) x <- as.av(x, ...) list( av = as.character(x), cid = av_cid(x), name = av_name(x, language = language), group = av_group(x, language = language), atc = av_atc(x), tradenames = av_tradenames(x), loinc = av_loinc(x), ddd = list( oral = list( amount = av_ddd(x, administration = "oral"), units = av_ddd_units(x, administration = "oral") ), iv = list( amount = av_ddd(x, administration = "iv"), units = av_ddd_units(x, administration = "iv") ) ) ) } #' @rdname av_property #' @export av_url <- function(x, open = FALSE, ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(open, allow_class = "logical", has_length = 1) av <- as.av(x = x, ...) atcs <- av_atc(av, only_first = TRUE) u <- paste0("https://www.whocc.no/atc_ddd_index/?code=", atcs, "&showdescription=no") u[is.na(atcs)] <- NA_character_ names(u) <- av_name(av) NAs <- av_name(av, tolower = TRUE, language = NULL)[!is.na(av) & is.na(atcs)] if (length(NAs) > 0) { warning_("in `av_url()`: no ATC code available for ", vector_and(NAs, quotes = FALSE), ".") } if (open == TRUE) { if (length(u) > 1 && !is.na(u[1L])) { warning_("in `av_url()`: only the first URL will be opened, as `browseURL()` only suports one string.") } if (!is.na(u[1L])) { utils::browseURL(u[1L]) } } u } #' @rdname av_property #' @export av_property <- function(x, property = "name", language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) meet_criteria(property, is_in = colnames(AMR::antivirals), has_length = 1) language <- validate_language(language) translate_into_language(av_validate(x = x, property = property, ...), language = language) } av_validate <- function(x, property, ...) { if (tryCatch(all(x[!is.na(x)] %in% AMR_env$AV_lookup$av), error = function(e) FALSE)) { # special case for av_* functions where class is already 'av' x <- AMR_env$AV_lookup[match(x, AMR_env$AV_lookup$av), property, drop = TRUE] } else { # try to catch an error when inputting an invalid argument # so the 'call.' can be set to FALSE tryCatch(x[1L] %in% AMR_env$AV_lookup[1, property, drop = TRUE], error = function(e) stop(e$message, call. = FALSE) ) if (!all(x %in% AMR_env$AV_lookup[, property, drop = TRUE])) { x <- as.av(x, ...) if (all(is.na(x)) && is.list(AMR_env$AV_lookup[, property, drop = TRUE])) { x <- rep(NA_character_, length(x)) } else { x <- AMR_env$AV_lookup[match(x, AMR_env$AV_lookup$av), property, drop = TRUE] } } } if (property == "av") { return(set_clean_class(x, new_class = c("av", "character"))) } else if (property == "cid") { return(as.integer(x)) } else if (property %like% "ddd") { return(as.double(x)) } else { x[is.na(x)] <- NA return(x) } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/av_property.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Check Availability of Columns #' #' Easy check for data availability of all columns in a data set. This makes it easy to get an idea of which antimicrobial combinations can be used for calculation with e.g. [susceptibility()] and [resistance()]. #' @param tbl a [data.frame] or [list] #' @param width number of characters to present the visual availability - the default is filling the width of the console #' @details The function returns a [data.frame] with columns `"resistant"` and `"visual_resistance"`. The values in that columns are calculated with [resistance()]. #' @return [data.frame] with column names of `tbl` as row names #' @export #' @examples #' availability(example_isolates) #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' filter(mo == as.mo("Escherichia coli")) %>% #' select_if(is.sir) %>% #' availability() #' } #' } availability <- function(tbl, width = NULL) { meet_criteria(tbl, allow_class = "data.frame") meet_criteria(width, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive = TRUE, is_finite = TRUE) tbl <- as.data.frame(tbl, stringsAsFactors = FALSE) x <- vapply(FUN.VALUE = double(1), tbl, function(x) { 1 - sum(is.na(x)) / length(x) }) n <- vapply(FUN.VALUE = double(1), tbl, function(x) length(x[!is.na(x)])) R <- vapply(FUN.VALUE = double(1), tbl, function(x) ifelse(is.sir(x), resistance(x, minimum = 0), NA_real_)) R_print <- character(length(R)) R_print[!is.na(R)] <- percentage(R[!is.na(R)]) R_print[is.na(R)] <- "" if (is.null(width)) { width <- getOption("width", 100) - (max(nchar(colnames(tbl))) + # count col 8 + # available % column 10 + # resistant % column 10 + # extra margin 5) width <- width / 2 } if (length(R[is.na(R)]) == ncol(tbl)) { width <- width * 2 + 10 } x_chars_R <- strrep("#", round(width * R, digits = 2)) x_chars_SI <- strrep("-", width - nchar(x_chars_R)) vis_resistance <- paste0("|", x_chars_R, x_chars_SI, "|") vis_resistance[is.na(R)] <- "" x_chars <- strrep("#", round(x, digits = 2) / (1 / width)) x_chars_empty <- strrep("-", width - nchar(x_chars)) df <- data.frame( count = n, available = percentage(x), visual_availabilty = paste0("|", x_chars, x_chars_empty, "|"), resistant = R_print, visual_resistance = vis_resistance, stringsAsFactors = FALSE ) if (length(R[is.na(R)]) == ncol(tbl)) { df[, 1:3, drop = FALSE] } else { df } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/availability.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Determine Bug-Drug Combinations #' #' Determine antimicrobial resistance (AMR) of all bug-drug combinations in your data set where at least 30 (default) isolates are available per species. Use [format()] on the result to prettify it to a publishable/printable format, see *Examples*. #' @inheritParams eucast_rules #' @param combine_SI a [logical] to indicate whether values S and I should be summed, so resistance will be based on only R - the default is `TRUE` #' @param add_ab_group a [logical] to indicate where the group of the antimicrobials must be included as a first column #' @param remove_intrinsic_resistant [logical] to indicate that rows and columns with 100% resistance for all tested antimicrobials must be removed from the table #' @param FUN the function to call on the `mo` column to transform the microorganism codes - the default is [mo_shortname()] #' @param translate_ab a [character] of length 1 containing column names of the [antibiotics] data set #' @param ... arguments passed on to `FUN` #' @inheritParams sir_df #' @inheritParams base::formatC #' @details The function [format()] calculates the resistance per bug-drug combination and returns a table ready for reporting/publishing. Use `combine_SI = TRUE` (default) to test R vs. S+I and `combine_SI = FALSE` to test R+I vs. S. This table can also directly be used in R Markdown / Quarto without the need for e.g. [knitr::kable()]. #' @export #' @rdname bug_drug_combinations #' @return The function [bug_drug_combinations()] returns a [data.frame] with columns "mo", "ab", "S", "I", "R" and "total". #' @examples #' # example_isolates is a data set available in the AMR package. #' # run ?example_isolates for more info. #' example_isolates #' #' \donttest{ #' x <- bug_drug_combinations(example_isolates) #' head(x) #' format(x, translate_ab = "name (atc)") #' #' # Use FUN to change to transformation of microorganism codes #' bug_drug_combinations(example_isolates, #' FUN = mo_gramstain #' ) #' #' bug_drug_combinations(example_isolates, #' FUN = function(x) { #' ifelse(x == as.mo("Escherichia coli"), #' "E. coli", #' "Others" #' ) #' } #' ) #' } bug_drug_combinations <- function(x, col_mo = NULL, FUN = mo_shortname, ...) { meet_criteria(x, allow_class = "data.frame", contains_column_class = c("sir", "rsi")) meet_criteria(col_mo, allow_class = "character", is_in = colnames(x), has_length = 1, allow_NULL = TRUE) meet_criteria(FUN, allow_class = "function", has_length = 1) # try to find columns based on type # -- mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo") stop_if(is.null(col_mo), "`col_mo` must be set") } else { stop_ifnot(col_mo %in% colnames(x), "column '", col_mo, "' (`col_mo`) not found") } x.bak <- x x <- as.data.frame(x, stringsAsFactors = FALSE) x[, col_mo] <- FUN(x[, col_mo, drop = TRUE], ...) unique_mo <- sort(unique(x[, col_mo, drop = TRUE])) # select only groups and antibiotics if (is_null_or_grouped_tbl(x.bak)) { data_has_groups <- TRUE groups <- get_group_names(x.bak) x <- x[, c(groups, col_mo, colnames(x)[vapply(FUN.VALUE = logical(1), x, is.sir)]), drop = FALSE] } else { data_has_groups <- FALSE x <- x[, c(col_mo, names(which(vapply(FUN.VALUE = logical(1), x, is.sir)))), drop = FALSE] } run_it <- function(x) { out <- data.frame( mo = character(0), ab = character(0), S = integer(0), I = integer(0), R = integer(0), total = integer(0), stringsAsFactors = FALSE ) if (data_has_groups) { group_values <- unique(x[, which(colnames(x) %in% groups), drop = FALSE]) rownames(group_values) <- NULL x <- x[, which(!colnames(x) %in% groups), drop = FALSE] } for (i in seq_len(length(unique_mo))) { # filter on MO group and only select SIR columns x_mo_filter <- x[which(x[, col_mo, drop = TRUE] == unique_mo[i]), names(which(vapply(FUN.VALUE = logical(1), x, is.sir))), drop = FALSE] # turn and merge everything pivot <- lapply(x_mo_filter, function(x) { m <- as.matrix(table(x)) data.frame(S = m["S", ], I = m["I", ], R = m["R", ], stringsAsFactors = FALSE) }) merged <- do.call(rbind_AMR, pivot) out_group <- data.frame( mo = rep(unique_mo[i], NROW(merged)), ab = rownames(merged), S = merged$S, I = merged$I, R = merged$R, total = merged$S + merged$I + merged$R, stringsAsFactors = FALSE ) if (data_has_groups) { if (nrow(group_values) < nrow(out_group)) { # repeat group_values for the number of rows in out_group repeated <- rep(seq_len(nrow(group_values)), each = nrow(out_group) / nrow(group_values) ) group_values <- group_values[repeated, , drop = FALSE] } out_group <- cbind(group_values, out_group) } out <- rbind_AMR(out, out_group) } out } # based on pm_apply_grouped_function apply_group <- function(.data, fn, groups, drop = FALSE, ...) { grouped <- pm_split_into_groups(.data, groups, drop) res <- do.call(rbind_AMR, unname(lapply(grouped, fn, ...))) if (any(groups %in% colnames(res))) { class(res) <- c("grouped_data", class(res)) res <- pm_set_groups(res, groups[groups %in% colnames(res)]) } res } if (data_has_groups) { out <- apply_group(x, "run_it", groups) } else { out <- run_it(x) } out <- out %pm>% pm_arrange(mo, ab) out <- as_original_data_class(out, class(x.bak)) # will remove tibble groups rownames(out) <- NULL structure(out, class = c("bug_drug_combinations", ifelse(data_has_groups, "grouped", character(0)), class(out))) } #' @method format bug_drug_combinations #' @export #' @rdname bug_drug_combinations format.bug_drug_combinations <- function(x, translate_ab = "name (ab, atc)", language = get_AMR_locale(), minimum = 30, combine_SI = TRUE, add_ab_group = TRUE, remove_intrinsic_resistant = FALSE, decimal.mark = getOption("OutDec"), big.mark = ifelse(decimal.mark == ",", ".", ","), ...) { meet_criteria(x, allow_class = "data.frame") meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE) language <- validate_language(language) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(add_ab_group, allow_class = "logical", has_length = 1) meet_criteria(remove_intrinsic_resistant, allow_class = "logical", has_length = 1) meet_criteria(decimal.mark, allow_class = "character", has_length = 1) meet_criteria(big.mark, allow_class = "character", has_length = 1) x.bak <- x if (inherits(x, "grouped")) { # bug_drug_combinations() has been run on groups, so de-group here warning_("in `format()`: formatting the output of `bug_drug_combinations()` does not support grouped variables, they were ignored") x <- as.data.frame(x, stringsAsFactors = FALSE) idx <- split(seq_len(nrow(x)), paste0(x$mo, "%%", x$ab)) x <- data.frame( mo = gsub("(.*)%%(.*)", "\\1", names(idx)), ab = gsub("(.*)%%(.*)", "\\2", names(idx)), S = vapply(FUN.VALUE = double(1), idx, function(i) sum(x$S[i], na.rm = TRUE)), I = vapply(FUN.VALUE = double(1), idx, function(i) sum(x$I[i], na.rm = TRUE)), R = vapply(FUN.VALUE = double(1), idx, function(i) sum(x$R[i], na.rm = TRUE)), total = vapply(FUN.VALUE = double(1), idx, function(i) { sum(x$S[i], na.rm = TRUE) + sum(x$I[i], na.rm = TRUE) + sum(x$R[i], na.rm = TRUE) }), stringsAsFactors = FALSE ) } x <- as.data.frame(x, stringsAsFactors = FALSE) x <- subset(x, total >= minimum) if (remove_intrinsic_resistant == TRUE) { x <- subset(x, R != total) } if (combine_SI == TRUE) { x$isolates <- x$R } else { x$isolates <- x$R + x$I } give_ab_name <- function(ab, format, language) { format <- tolower(format) ab_txt <- rep(format, length(ab)) for (i in seq_len(length(ab_txt))) { ab_txt[i] <- gsub("ab", as.character(as.ab(ab[i])), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("cid", ab_cid(ab[i]), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("group", ab_group(ab[i], language = language), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("atc_group1", ab_atc_group1(ab[i], language = language), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("atc_group2", ab_atc_group2(ab[i], language = language), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("atc", ab_atc(ab[i], only_first = TRUE), ab_txt[i], fixed = TRUE) ab_txt[i] <- gsub("name", ab_name(ab[i], language = language), ab_txt[i], fixed = TRUE) ab_txt[i] } ab_txt } remove_NAs <- function(.data) { cols <- colnames(.data) .data <- as.data.frame(lapply(.data, function(x) ifelse(is.na(x), "", x)), stringsAsFactors = FALSE ) colnames(.data) <- cols .data } create_var <- function(.data, ...) { dots <- list(...) for (i in seq_len(length(dots))) { .data[, names(dots)[i]] <- dots[[i]] } .data } y <- x %pm>% create_var( ab = as.ab(x$ab), ab_txt = give_ab_name(ab = x$ab, format = translate_ab, language = language) ) %pm>% pm_group_by(ab, ab_txt, mo) %pm>% pm_summarise( isolates = sum(isolates, na.rm = TRUE), total = sum(total, na.rm = TRUE) ) %pm>% pm_ungroup() y <- y %pm>% create_var(txt = paste0( percentage(y$isolates / y$total, decimal.mark = decimal.mark, big.mark = big.mark), " (", trimws(format(y$isolates, big.mark = big.mark)), "/", trimws(format(y$total, big.mark = big.mark)), ")" )) %pm>% pm_select(ab, ab_txt, mo, txt) %pm>% pm_arrange(mo) # replace tidyr::pivot_wider() from here for (i in unique(y$mo)) { mo_group <- y[which(y$mo == i), c("ab", "txt"), drop = FALSE] colnames(mo_group) <- c("ab", i) rownames(mo_group) <- NULL y <- y %pm>% pm_left_join(mo_group, by = "ab") } y <- y %pm>% pm_distinct(ab, .keep_all = TRUE) %pm>% pm_select(-mo, -txt) %pm>% # replace tidyr::pivot_wider() until here remove_NAs() select_ab_vars <- function(.data) { .data[, c("ab_group", "ab_txt", colnames(.data)[!colnames(.data) %in% c("ab_group", "ab_txt", "ab")]), drop = FALSE] } y <- y %pm>% create_var(ab_group = ab_group(y$ab, language = language)) %pm>% select_ab_vars() %pm>% pm_arrange(ab_group, ab_txt) y <- y %pm>% create_var(ab_group = ifelse(y$ab_group != pm_lag(y$ab_group) | is.na(pm_lag(y$ab_group)), y$ab_group, "")) if (add_ab_group == FALSE) { y <- y %pm>% pm_select(-ab_group) %pm>% pm_rename("Drug" = ab_txt) colnames(y)[1] <- translate_into_language(colnames(y)[1], language, only_unknown = FALSE) } else { y <- y %pm>% pm_rename( "Group" = ab_group, "Drug" = ab_txt ) } if (!is.null(language)) { colnames(y) <- translate_into_language(colnames(y), language, only_unknown = FALSE) } if (remove_intrinsic_resistant == TRUE) { y <- y[, !vapply(FUN.VALUE = logical(1), y, function(col) all(col %like% "100", na.rm = TRUE) & !anyNA(col)), drop = FALSE] } rownames(y) <- NULL as_original_data_class(y, class(x.bak), extra_class = "formatted_bug_drug_combinations") # will remove tibble groups } # will be exported in zzz.R knit_print.formatted_bug_drug_combinations <- function(x, ...) { stop_ifnot_installed("knitr") # make columns with MO names italic according to nomenclature colnames(x)[3:NCOL(x)] <- italicise_taxonomy(colnames(x)[3:NCOL(x)], type = "markdown") knitr::asis_output(paste("", "", knitr::kable(x, ...), collapse = "\n")) } #' @method print bug_drug_combinations #' @export print.bug_drug_combinations <- function(x, ...) { x_class <- class(x) print( set_clean_class(x, new_class = x_class[!x_class %in% c("bug_drug_combinations", "grouped")] ), ... ) message_("Use 'format()' on this result to get a publishable/printable format.", ifelse(inherits(x, "grouped"), " Note: The grouping variable(s) will be ignored.", ""), as_note = FALSE ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/bug_drug_combinations.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Count Available Isolates #' #' @description These functions can be used to count resistant/susceptible microbial isolates. All functions support quasiquotation with pipes, can be used in `summarise()` from the `dplyr` package and also support grouped variables, see *Examples*. #' #' [count_resistant()] should be used to count resistant isolates, [count_susceptible()] should be used to count susceptible isolates. #' @param ... one or more vectors (or columns) with antibiotic interpretations. They will be transformed internally with [as.sir()] if needed. #' @inheritParams proportion #' @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 [count_resistant()] is equal to the function [count_R()]. The function [count_susceptible()] is equal to the function [count_SI()]. #' #' The function [n_sir()] is an alias of [count_all()]. They can be used to count all available isolates, i.e. where all input antibiotics have an available result (S, I or R). Their use is equal to `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 #' @seealso [`proportion_*`][proportion] to calculate microbial resistance and susceptibility. #' @return An [integer] #' @rdname count #' @name count #' @export #' @examples #' # example_isolates is a data set available in the AMR package. #' # run ?example_isolates for more info. #' #' # base R ------------------------------------------------------------ #' count_resistant(example_isolates$AMX) # counts "R" #' count_susceptible(example_isolates$AMX) # counts "S" and "I" #' count_all(example_isolates$AMX) # counts "S", "I" and "R" #' #' # be more specific #' count_S(example_isolates$AMX) #' count_SI(example_isolates$AMX) #' count_I(example_isolates$AMX) #' count_IR(example_isolates$AMX) #' count_R(example_isolates$AMX) #' #' # Count all available isolates #' count_all(example_isolates$AMX) #' n_sir(example_isolates$AMX) #' #' # n_sir() is an alias of count_all(). #' # Since it counts all available isolates, you can #' # calculate back to count e.g. susceptible isolates. #' # These results are the same: #' count_susceptible(example_isolates$AMX) #' susceptibility(example_isolates$AMX) * n_sir(example_isolates$AMX) #' #' # dplyr ------------------------------------------------------------- #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' group_by(ward) %>% #' summarise( #' R = count_R(CIP), #' I = count_I(CIP), #' S = count_S(CIP), #' n1 = count_all(CIP), # the actual total; sum of all three #' n2 = n_sir(CIP), # same - analogous to n_distinct #' total = n() #' ) # NOT the number of tested isolates! #' #' # Number of available isolates for a whole antibiotic class #' # (i.e., in this data set columns GEN, TOB, AMK, KAN) #' example_isolates %>% #' group_by(ward) %>% #' summarise(across(aminoglycosides(), n_sir)) #' #' # Count co-resistance between amoxicillin/clav acid and gentamicin, #' # so we can see that combination therapy does a lot more than mono therapy. #' # Please mind that `susceptibility()` calculates percentages right away instead. #' example_isolates %>% count_susceptible(AMC) # 1433 #' example_isolates %>% count_all(AMC) # 1879 #' #' example_isolates %>% count_susceptible(GEN) # 1399 #' example_isolates %>% count_all(GEN) # 1855 #' #' example_isolates %>% count_susceptible(AMC, GEN) # 1764 #' example_isolates %>% count_all(AMC, GEN) # 1936 #' #' # Get number of S+I vs. R immediately of selected columns #' example_isolates %>% #' select(AMX, CIP) %>% #' count_df(translate = FALSE) #' #' # It also supports grouping variables #' example_isolates %>% #' select(ward, AMX, CIP) %>% #' group_by(ward) %>% #' count_df(translate = FALSE) #' } #' } count_resistant <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "R", only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export count_susceptible <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("S", "I"), only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export count_R <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "R", only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export 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) } tryCatch( sir_calc(..., ab_result = c("I", "R"), only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export count_I <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "I", only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export count_SI <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("S", "I"), only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export 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) } tryCatch( sir_calc(..., ab_result = "S", only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export count_all <- function(..., only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("S", "I", "R"), only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname count #' @export n_sir <- count_all #' @rdname count #' @export count_df <- function(data, translate_ab = "name", language = get_AMR_locale(), combine_SI = TRUE) { tryCatch( sir_calc_df( type = "count", data = data, translate_ab = translate_ab, language = language, combine_SI = combine_SI, confidence_level = 0.95 # doesn't matter, will be removed ), error = function(e) stop_(gsub("in sir_calc_df(): ", "", e$message, fixed = TRUE), call = -5) ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/count.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Add Custom Antimicrobials #' #' With [add_custom_antimicrobials()] you can add your own custom antimicrobial drug names and codes. #' @param x a [data.frame] resembling the [antibiotics] data set, at least containing columns "ab" and "name" #' @details **Important:** Due to how \R works, the [add_custom_antimicrobials()] function has to be run in every \R session - added antimicrobials are not stored between sessions and are thus lost when \R is exited. #' #' There are two ways to circumvent this and automate the process of adding antimicrobials: #' #' **Method 1:** Using the [package option][AMR-options] [`AMR_custom_ab`][AMR-options], which is the preferred method. To use this method: #' #' 1. Create a data set in the structure of the [antibiotics] data set (containing at the very least columns "ab" and "name") and save it with [saveRDS()] to a location of choice, e.g. `"~/my_custom_ab.rds"`, or any remote location. #' #' 2. Set the file location to the [package option][AMR-options] [`AMR_custom_ab`][AMR-options]: `options(AMR_custom_ab = "~/my_custom_ab.rds")`. This can even be a remote file location, such as an https URL. Since options are not saved between \R sessions, it is best to save this option to the `.Rprofile` file so that it will be loaded on start-up of \R. To do this, open the `.Rprofile` file using e.g. `utils::file.edit("~/.Rprofile")`, add this text and save the file: #' #' ```r #' # Add custom antimicrobial codes: #' options(AMR_custom_ab = "~/my_custom_ab.rds") #' ``` #' #' Upon package load, this file will be loaded and run through the [add_custom_antimicrobials()] function. #' #' **Method 2:** Loading the antimicrobial additions directly from your `.Rprofile` file. Note that the definitions will be stored in a user-specific \R file, which is a suboptimal workflow. To use this method: #' #' 1. Edit the `.Rprofile` file using e.g. `utils::file.edit("~/.Rprofile")`. #' #' 2. Add a text like below and save the file: #' #' ```r #' # Add custom antibiotic drug codes: #' AMR::add_custom_antimicrobials( #' data.frame(ab = "TESTAB", #' name = "Test Antibiotic", #' group = "Test Group") #' ) #' ``` #' #' Use [clear_custom_antimicrobials()] to clear the previously added antimicrobials. #' @seealso [add_custom_microorganisms()] to add custom microorganisms. #' @rdname add_custom_antimicrobials #' @export #' @examples #' \donttest{ #' #' # returns NA and throws a warning (which is suppressed here): #' suppressWarnings( #' as.ab("testab") #' ) #' #' # now add a custom entry - it will be considered by as.ab() and #' # all ab_*() functions #' add_custom_antimicrobials( #' data.frame( #' ab = "TESTAB", #' name = "Test Antibiotic", #' # you can add any property present in the #' # 'antibiotics' data set, such as 'group': #' group = "Test Group" #' ) #' ) #' #' # "testab" is now a new antibiotic: #' as.ab("testab") #' ab_name("testab") #' ab_group("testab") #' #' ab_info("testab") #' #' #' # Add Co-fluampicil, which is one of the many J01CR50 codes, see #' # https://www.whocc.no/ddd/list_of_ddds_combined_products/ #' add_custom_antimicrobials( #' data.frame( #' ab = "COFLU", #' name = "Co-fluampicil", #' atc = "J01CR50", #' group = "Beta-lactams/penicillins" #' ) #' ) #' ab_atc("Co-fluampicil") #' ab_name("J01CR50") #' #' # even antibiotic selectors work #' x <- data.frame( #' random_column = "some value", #' coflu = as.sir("S"), #' ampicillin = as.sir("R") #' ) #' x #' x[, betalactams()] #' } add_custom_antimicrobials <- function(x) { meet_criteria(x, allow_class = "data.frame") stop_ifnot( all(c("ab", "name") %in% colnames(x)), "`x` must contain columns \"ab\" and \"name\"." ) stop_if( any(x$ab %in% AMR_env$AB_lookup$ab), "Antimicrobial drug code(s) ", vector_and(x$ab[x$ab %in% AMR_env$AB_lookup$ab]), " already exist in the internal `antibiotics` data set." ) # remove any extra class/type, such as grouped tbl, or data.table: x <- as.data.frame(x, stringsAsFactors = FALSE) # keep only columns available in the antibiotics data set x <- x[, colnames(AMR_env$AB_lookup)[colnames(AMR_env$AB_lookup) %in% colnames(x)], drop = FALSE] x$generalised_name <- generalise_antibiotic_name(x$name) x$generalised_all <- as.list(x$generalised_name) for (col in colnames(x)) { if (is.list(AMR_env$AB_lookup[, col, drop = TRUE]) & !is.list(x[, col, drop = TRUE])) { x[, col] <- as.list(x[, col, drop = TRUE]) } } AMR_env$custom_ab_codes <- c(AMR_env$custom_ab_codes, x$ab) class(AMR_env$AB_lookup$ab) <- "character" new_df <- AMR_env$AB_lookup[0, , drop = FALSE][seq_len(NROW(x)), , drop = FALSE] rownames(new_df) <- NULL list_cols <- vapply(FUN.VALUE = logical(1), new_df, is.list) for (l in which(list_cols)) { # prevent binding NULLs in lists, replace with NA new_df[, l] <- as.list(NA_character_) } for (col in colnames(x)) { # assign new values new_df[, col] <- x[, col, drop = TRUE] } AMR_env$AB_lookup <- unique(rbind_AMR(AMR_env$AB_lookup, new_df)) AMR_env$ab_previously_coerced <- AMR_env$ab_previously_coerced[which(!AMR_env$ab_previously_coerced$ab %in% x$ab), , drop = FALSE] class(AMR_env$AB_lookup$ab) <- c("ab", "character") message_("Added ", nr2char(nrow(x)), " record", ifelse(nrow(x) > 1, "s", ""), " to the internal `antibiotics` data set.") } #' @rdname add_custom_antimicrobials #' @export clear_custom_antimicrobials <- function() { n <- nrow(AMR_env$AB_lookup) AMR_env$AB_lookup <- cbind(AMR::antibiotics, AB_LOOKUP) n2 <- nrow(AMR_env$AB_lookup) AMR_env$custom_ab_codes <- character(0) AMR_env$ab_previously_coerced <- AMR_env$ab_previously_coerced[which(AMR_env$ab_previously_coerced$ab %in% AMR_env$AB_lookup$ab), , drop = FALSE] message_("Cleared ", nr2char(n - n2), " custom record", ifelse(n - n2 > 1, "s", ""), " from the internal `antibiotics` data set.") }
/scratch/gouwar.j/cran-all/cranData/AMR/R/custom_antimicrobials.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Define Custom EUCAST Rules #' #' Define custom EUCAST rules for your organisation or specific analysis and use the output of this function in [eucast_rules()]. #' @param ... rules in [formula][base::tilde] notation, see *Examples* #' @details #' Some organisations have their own adoption of EUCAST rules. This function can be used to define custom EUCAST rules to be used in the [eucast_rules()] function. #' @section How it works: #' #' ### Basics #' #' If you are familiar with the [`case_when()`][dplyr::case_when()] function of the `dplyr` package, you will recognise the input method to set your own rules. Rules must be set using what \R considers to be the 'formula notation'. The rule itself is written *before* the tilde (`~`) and the consequence of the rule is written *after* the tilde: #' #' ```r #' x <- custom_eucast_rules(TZP == "S" ~ aminopenicillins == "S", #' TZP == "R" ~ aminopenicillins == "R") #' ``` #' #' These are two custom EUCAST rules: if TZP (piperacillin/tazobactam) is "S", all aminopenicillins (ampicillin and amoxicillin) must be made "S", and if TZP is "R", aminopenicillins must be made "R". These rules can also be printed to the console, so it is immediately clear how they work: #' #' ```r #' x #' #> A set of custom EUCAST rules: #' #> #' #> 1. If TZP is "S" then set to S : #' #> amoxicillin (AMX), ampicillin (AMP) #' #> #' #> 2. If TZP is "R" then set to R : #' #> amoxicillin (AMX), ampicillin (AMP) #' ``` #' #' The rules (the part *before* the tilde, in above example `TZP == "S"` and `TZP == "R"`) must be evaluable in your data set: it should be able to run as a filter in your data set without errors. This means for the above example that the column `TZP` must exist. We will create a sample data set and test the rules set: #' #' ```r #' df <- data.frame(mo = c("Escherichia coli", "Klebsiella pneumoniae"), #' TZP = as.sir("R"), #' ampi = as.sir("S"), #' cipro = as.sir("S")) #' df #' #> mo TZP ampi cipro #' #> 1 Escherichia coli R S S #' #> 2 Klebsiella pneumoniae R S S #' #' eucast_rules(df, rules = "custom", custom_rules = x, info = FALSE) #' #> mo TZP ampi cipro #' #> 1 Escherichia coli R R S #' #> 2 Klebsiella pneumoniae R R S #' ``` #' #' ### Using taxonomic properties in rules #' #' There is one exception in columns used for the rules: all column names of the [microorganisms] data set can also be used, but do not have to exist in the data set. These column names are: `r vector_and(colnames(microorganisms), sort = FALSE)`. Thus, this next example will work as well, despite the fact that the `df` data set does not contain a column `genus`: #' #' ```r #' y <- custom_eucast_rules(TZP == "S" & genus == "Klebsiella" ~ aminopenicillins == "S", #' TZP == "R" & genus == "Klebsiella" ~ aminopenicillins == "R") #' #' eucast_rules(df, rules = "custom", custom_rules = y, info = FALSE) #' #> mo TZP ampi cipro #' #> 1 Escherichia coli R S S #' #> 2 Klebsiella pneumoniae R R S #' ``` #' #' ### Usage of antibiotic group names #' #' It is possible to define antibiotic groups instead of single antibiotics for the rule consequence, the part *after* the tilde. In above examples, the antibiotic group `aminopenicillins` is used to include ampicillin and amoxicillin. The following groups are allowed (case-insensitive). Within parentheses are the drugs that will be matched when running the rule. #' #' `r paste0(" * ", sapply(DEFINED_AB_GROUPS, function(x) paste0("\"", tolower(gsub("^AB_", "", x)), "\"\\cr(", vector_and(ab_name(eval(parse(text = x), envir = asNamespace("AMR")), language = NULL, tolower = TRUE), quotes = FALSE), ")"), USE.NAMES = FALSE), "\n", collapse = "")` #' @returns A [list] containing the custom rules #' @export #' @examples #' x <- custom_eucast_rules( #' AMC == "R" & genus == "Klebsiella" ~ aminopenicillins == "R", #' AMC == "I" & genus == "Klebsiella" ~ aminopenicillins == "I" #' ) #' x #' #' # run the custom rule set (verbose = TRUE will return a logbook instead of the data set): #' eucast_rules(example_isolates, #' rules = "custom", #' custom_rules = x, #' info = FALSE, #' verbose = TRUE #' ) #' #' # combine rule sets #' x2 <- c( #' x, #' custom_eucast_rules(TZP == "R" ~ carbapenems == "R") #' ) #' x2 custom_eucast_rules <- function(...) { dots <- tryCatch(list(...), error = function(e) "error" ) stop_if( identical(dots, "error"), "rules must be a valid formula inputs (e.g., using '~'), see `?custom_eucast_rules`" ) n_dots <- length(dots) stop_if(n_dots == 0, "no custom rules were set. Please read the documentation using `?custom_eucast_rules`.") out <- vector("list", n_dots) for (i in seq_len(n_dots)) { stop_ifnot( inherits(dots[[i]], "formula"), "rule ", i, " must be a valid formula input (e.g., using '~'), see `?custom_eucast_rules`" ) # Query qry <- dots[[i]][[2]] if (inherits(qry, "call")) { qry <- as.expression(qry) } qry <- as.character(qry) # these will prevent vectorisation, so replace them: qry <- gsub("&&", "&", qry, fixed = TRUE) qry <- gsub("||", "|", qry, fixed = TRUE) # format nicely, setting spaces around operators qry <- gsub(" *([&|+-/*^><==]+) *", " \\1 ", qry) qry <- gsub(" ?, ?", ", ", qry) qry <- gsub("'", "\"", qry, fixed = TRUE) out[[i]]$query <- as.expression(qry) # Resulting rule result <- dots[[i]][[3]] stop_ifnot( deparse(result) %like% "==", "the result of rule ", i, " (the part after the `~`) must contain `==`, such as in `... ~ ampicillin == \"R\"`, see `?custom_eucast_rules`" ) result_group <- as.character(result)[[2]] if (paste0("AB_", toupper(result_group), "S") %in% DEFINED_AB_GROUPS) { # support for e.g. 'aminopenicillin' if user meant 'aminopenicillins' result_group <- paste0(result_group, "s") } if (paste0("AB_", toupper(result_group)) %in% DEFINED_AB_GROUPS) { result_group <- eval(parse(text = paste0("AB_", toupper(result_group))), envir = asNamespace("AMR")) } else { result_group <- tryCatch( suppressWarnings(as.ab(result_group, fast_mode = TRUE, flag_multiple_results = FALSE )), error = function(e) NA_character_ ) } stop_if( any(is.na(result_group)), "this result of rule ", i, " could not be translated to a single antimicrobial drug/group: \"", as.character(result)[[2]], "\".\n\nThe input can be a name or code of an antimicrobial drug, or be one of: ", vector_or(tolower(gsub("AB_", "", DEFINED_AB_GROUPS)), quotes = FALSE), "." ) result_value <- as.character(result)[[3]] result_value[result_value == "NA"] <- NA stop_ifnot( result_value %in% c("S", "I", "R", NA), "the resulting value of rule ", i, " must be either \"S\", \"I\", \"R\" or NA" ) result_value <- as.sir(result_value) out[[i]]$result_group <- result_group out[[i]]$result_value <- result_value } names(out) <- paste0("rule", seq_len(n_dots)) set_clean_class(out, new_class = c("custom_eucast_rules", "list")) } #' @method c custom_eucast_rules #' @noRd #' @export c.custom_eucast_rules <- function(x, ...) { if (length(list(...)) == 0) { return(x) } out <- unclass(x) for (e in list(...)) { out <- c(out, unclass(e)) } names(out) <- paste0("rule", seq_len(length(out))) set_clean_class(out, new_class = c("custom_eucast_rules", "list")) } #' @method as.list custom_eucast_rules #' @noRd #' @export as.list.custom_eucast_rules <- function(x, ...) { c(x, ...) } #' @method print custom_eucast_rules #' @export #' @noRd print.custom_eucast_rules <- function(x, ...) { cat("A set of custom EUCAST rules:\n") for (i in seq_len(length(x))) { rule <- x[[i]] rule$query <- format_custom_query_rule(rule$query) if (is.na(rule$result_value)) { val <- font_red("<NA>") } else if (rule$result_value == "R") { val <- font_red_bg(" R ") } else if (rule$result_value == "S") { val <- font_green_bg(" S ") } else { val <- font_orange_bg(" I ") } agents <- paste0( font_blue(ab_name(rule$result_group, language = NULL, tolower = TRUE), collapse = NULL ), " (", rule$result_group, ")" ) agents <- sort(agents) rule_if <- word_wrap( paste0( i, ". ", font_bold("If "), font_blue(rule$query), font_bold(" then "), "set to {result}:" ), extra_indent = 5 ) rule_if <- gsub("{result}", val, rule_if, fixed = TRUE) rule_then <- paste0(" ", word_wrap(paste0(agents, collapse = ", "), extra_indent = 5)) cat("\n ", rule_if, "\n", rule_then, "\n", sep = "") } } format_custom_query_rule <- function(query, colours = has_colour()) { # font_black() is a bit expensive so do it once: txt <- font_black("{text}") query <- gsub(" & ", sub("{text}", font_bold(" and "), txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" | ", sub("{text}", " or ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" + ", sub("{text}", " plus ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" - ", sub("{text}", " minus ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" / ", sub("{text}", " divided by ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" * ", sub("{text}", " times ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" == ", sub("{text}", " is ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" > ", sub("{text}", " is higher than ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" < ", sub("{text}", " is lower than ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" >= ", sub("{text}", " is higher than or equal to ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" <= ", sub("{text}", " is lower than or equal to ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" ^ ", sub("{text}", " to the power of ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" %in% ", sub("{text}", " is one of ", txt, fixed = TRUE), query, fixed = TRUE) query <- gsub(" %like% ", sub("{text}", " resembles ", txt, fixed = TRUE), query, fixed = TRUE) if (colours == TRUE) { query <- gsub('"R"', font_red_bg(" R "), query, fixed = TRUE) query <- gsub('"S"', font_green_bg(" S "), query, fixed = TRUE) query <- gsub('"I"', font_orange_bg(" I "), query, fixed = TRUE) } # replace the black colour 'stops' with blue colour 'starts' query <- gsub("\033[39m", "\033[34m", as.character(query), fixed = TRUE) # start with blue query <- paste0("\033[34m", query) if (colours == FALSE) { query <- font_stripstyle(query) } query }
/scratch/gouwar.j/cran-all/cranData/AMR/R/custom_eucast_rules.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Add Custom Microorganisms #' #' With [add_custom_microorganisms()] you can add your own custom microorganisms, such the non-taxonomic outcome of laboratory analysis. #' @param x a [data.frame] resembling the [microorganisms] data set, at least containing column "genus" (case-insensitive) #' @details This function will fill in missing taxonomy for you, if specific taxonomic columns are missing, see *Examples*. #' #' **Important:** Due to how \R works, the [add_custom_microorganisms()] function has to be run in every \R session - added microorganisms are not stored between sessions and are thus lost when \R is exited. #' #' There are two ways to circumvent this and automate the process of adding microorganisms: #' #' **Method 1:** Using the [package option][AMR-options] [`AMR_custom_mo`][AMR-options], which is the preferred method. To use this method: #' #' 1. Create a data set in the structure of the [microorganisms] data set (containing at the very least column "genus") and save it with [saveRDS()] to a location of choice, e.g. `"~/my_custom_mo.rds"`, or any remote location. #' #' 2. Set the file location to the [package option][AMR-options] [`AMR_custom_mo`][AMR-options]: `options(AMR_custom_mo = "~/my_custom_mo.rds")`. This can even be a remote file location, such as an https URL. Since options are not saved between \R sessions, it is best to save this option to the `.Rprofile` file so that it will be loaded on start-up of \R. To do this, open the `.Rprofile` file using e.g. `utils::file.edit("~/.Rprofile")`, add this text and save the file: #' #' ```r #' # Add custom microorganism codes: #' options(AMR_custom_mo = "~/my_custom_mo.rds") #' ``` #' #' Upon package load, this file will be loaded and run through the [add_custom_microorganisms()] function. #' #' **Method 2:** Loading the microorganism directly from your `.Rprofile` file. Note that the definitions will be stored in a user-specific \R file, which is a suboptimal workflow. To use this method: #' #' 1. Edit the `.Rprofile` file using e.g. `utils::file.edit("~/.Rprofile")`. #' #' 2. Add a text like below and save the file: #' #' ```r #' # Add custom antibiotic drug codes: #' AMR::add_custom_microorganisms( #' data.frame(genus = "Enterobacter", #' species = "asburiae/cloacae") #' ) #' ``` #' #' Use [clear_custom_microorganisms()] to clear the previously added microorganisms. #' @seealso [add_custom_antimicrobials()] to add custom antimicrobials. #' @rdname add_custom_microorganisms #' @export #' @examples #' \donttest{ #' # a combination of species is not formal taxonomy, so #' # this will result in "Enterobacter cloacae cloacae", #' # since it resembles the input best: #' mo_name("Enterobacter asburiae/cloacae") #' #' # now add a custom entry - it will be considered by as.mo() and #' # all mo_*() functions #' add_custom_microorganisms( #' data.frame( #' genus = "Enterobacter", #' species = "asburiae/cloacae" #' ) #' ) #' #' # E. asburiae/cloacae is now a new microorganism: #' mo_name("Enterobacter asburiae/cloacae") #' #' # its code: #' as.mo("Enterobacter asburiae/cloacae") #' #' # all internal algorithms will work as well: #' mo_name("Ent asburia cloacae") #' #' # and even the taxonomy was added based on the genus! #' mo_family("E. asburiae/cloacae") #' mo_gramstain("Enterobacter asburiae/cloacae") #' #' mo_info("Enterobacter asburiae/cloacae") #' #' #' # the function tries to be forgiving: #' add_custom_microorganisms( #' data.frame( #' GENUS = "BACTEROIDES / PARABACTEROIDES SLASHLINE", #' SPECIES = "SPECIES" #' ) #' ) #' mo_name("BACTEROIDES / PARABACTEROIDES") #' mo_rank("BACTEROIDES / PARABACTEROIDES") #' #' # taxonomy still works, even though a slashline genus was given as input: #' mo_family("Bacteroides/Parabacteroides") #' #' #' # for groups and complexes, set them as species or subspecies: #' add_custom_microorganisms( #' data.frame( #' genus = "Citrobacter", #' species = c("freundii", "braakii complex"), #' subspecies = c("complex", "") #' ) #' ) #' mo_name(c("C. freundii complex", "C. braakii complex")) #' mo_species(c("C. freundii complex", "C. braakii complex")) #' mo_gramstain(c("C. freundii complex", "C. braakii complex")) #' } add_custom_microorganisms <- function(x) { meet_criteria(x, allow_class = "data.frame") stop_ifnot("genus" %in% tolower(colnames(x)), paste0("`x` must contain column 'genus'.")) add_MO_lookup_to_AMR_env() # remove any extra class/type, such as grouped tbl, or data.table: x <- as.data.frame(x, stringsAsFactors = FALSE) colnames(x) <- tolower(colnames(x)) # rename 'name' to 'fullname' if it's in the data set if ("name" %in% colnames(x) && !"fullname" %in% colnames(x)) { colnames(x)[colnames(x) == "name"] <- "fullname" } # keep only columns available in the microorganisms data set x <- x[, colnames(AMR_env$MO_lookup)[colnames(AMR_env$MO_lookup) %in% colnames(x)], drop = FALSE] # clean the input ---- for (col in c("genus", "species", "subspecies")) { if (!col %in% colnames(x)) { x[, col] <- "" } if (is.factor(x[, col, drop = TRUE])) { x[, col] <- as.character(x[, col, drop = TRUE]) } col_ <- x[, col, drop = TRUE] col_ <- tolower(col_) col_ <- gsub("slashline", "", col_, fixed = TRUE) col_ <- trimws2(col_) col_[col_ %like% "(sub)?species"] <- "" col_ <- gsub(" *([/-]) *", "\\1", col_, perl = TRUE) # groups are in our taxonomic table with a capital G col_ <- gsub(" group( |$)", " Group\\1", col_, perl = TRUE) col_[is.na(col_)] <- "" if (col == "genus") { substr(col_, 1, 1) <- toupper(substr(col_, 1, 1)) col_ <- gsub("/([a-z])", "/\\U\\1", col_, perl = TRUE) stop_if(any(col_ == ""), "the 'genus' column cannot be empty") stop_if(any(col_ %like% " "), "the 'genus' column must not contain spaces") } x[, col] <- col_ } # if subspecies is a group or complex, add it to the species and empty the subspecies x$species[which(x$subspecies %in% c("group", "Group", "complex"))] <- paste( x$species[which(x$subspecies %in% c("group", "Group", "complex"))], x$subspecies[which(x$subspecies %in% c("group", "Group", "complex"))] ) x$subspecies[which(x$subspecies %in% c("group", "Group", "complex"))] <- "" if ("rank" %in% colnames(x)) { stop_ifnot( all(x$rank %in% AMR_env$MO_lookup$rank), "the 'rank' column can only contain these values: ", vector_or(AMR_env$MO_lookup$rank) ) } else { x$rank <- ifelse(x$subspecies != "", "subspecies", ifelse(x$species != "", "species", ifelse(x$genus != "", "genus", stop("in add_custom_microorganisms(): only microorganisms up to the genus level can be added", call. = FALSE ) ) ) ) } x$source <- "Added by user" if (!"fullname" %in% colnames(x)) { x$fullname <- trimws2(paste(x$genus, x$species, x$subspecies)) } if (!"kingdom" %in% colnames(x)) x$kingdom <- "" if (!"phylum" %in% colnames(x)) x$phylum <- "" if (!"class" %in% colnames(x)) x$class <- "" if (!"order" %in% colnames(x)) x$order <- "" if (!"family" %in% colnames(x)) x$family <- "" x$kingdom[is.na(x$kingdom)] <- "" x$phylum[is.na(x$phylum)] <- "" x$class[is.na(x$class)] <- "" x$order[is.na(x$order)] <- "" x$family[is.na(x$family)] <- "" for (col in colnames(x)) { if (is.factor(x[, col, drop = TRUE])) { x[, col] <- as.character(x[, col, drop = TRUE]) } if (is.list(AMR_env$MO_lookup[, col, drop = TRUE])) { x[, col] <- as.list(x[, col, drop = TRUE]) } } # fill in taxonomy based on genus genus_to_check <- gsub("^(.*)[^a-zA-Z].*", "\\1", x$genus, perl = TRUE) x$kingdom[which(x$kingdom == "" & genus_to_check != "")] <- AMR_env$MO_lookup$kingdom[match(genus_to_check[which(x$kingdom == "" & genus_to_check != "")], AMR_env$MO_lookup$genus)] x$phylum[which(x$phylum == "" & genus_to_check != "")] <- AMR_env$MO_lookup$phylum[match(genus_to_check[which(x$phylum == "" & genus_to_check != "")], AMR_env$MO_lookup$genus)] x$class[which(x$class == "" & genus_to_check != "")] <- AMR_env$MO_lookup$class[match(genus_to_check[which(x$class == "" & genus_to_check != "")], AMR_env$MO_lookup$genus)] x$order[which(x$order == "" & genus_to_check != "")] <- AMR_env$MO_lookup$order[match(genus_to_check[which(x$order == "" & genus_to_check != "")], AMR_env$MO_lookup$genus)] x$family[which(x$family == "" & genus_to_check != "")] <- AMR_env$MO_lookup$family[match(genus_to_check[which(x$family == "" & genus_to_check != "")], AMR_env$MO_lookup$genus)] # fill in other columns that are used in internal algorithms x$prevalence <- NA_real_ x$prevalence[which(genus_to_check != "")] <- AMR_env$MO_lookup$prevalence[match(genus_to_check[which(genus_to_check != "")], AMR_env$MO_lookup$genus)] x$prevalence[is.na(x$prevalence)] <- 1.25 x$status <- "accepted" x$ref <- paste("Self-added,", format(Sys.Date(), "%Y")) x$kingdom_index <- AMR_env$MO_lookup$kingdom_index[match(genus_to_check, AMR_env$MO_lookup$genus)] # complete missing kingdom index, so mo_matching_score() will not return NA x$kingdom_index[is.na(x$kingdom_index)] <- 1 x$fullname_lower <- tolower(x$fullname) x$full_first <- substr(x$fullname_lower, 1, 1) x$species_first <- tolower(substr(x$species, 1, 1)) x$subspecies_first <- tolower(substr(x$subspecies, 1, 1)) if (!"mo" %in% colnames(x)) { # create the mo code x$mo <- NA_character_ } x$mo <- trimws2(as.character(x$mo)) x$mo[x$mo == ""] <- NA_character_ current <- sum(AMR_env$MO_lookup$source == "Added by user", na.rm = TRUE) x$mo[is.na(x$mo)] <- paste0( "CUSTOM", seq.int(from = current + 1, to = current + nrow(x), by = 1), "_", trimws( paste(abbreviate_mo(x$genus, 5), abbreviate_mo(x$species, 4, hyphen_as_space = TRUE), abbreviate_mo(x$subspecies, 4, hyphen_as_space = TRUE), sep = "_"), whitespace = "_")) stop_if(anyDuplicated(c(as.character(AMR_env$MO_lookup$mo), x$mo)), "MO codes must be unique and not match existing MO codes of the AMR package") # add to package ---- AMR_env$custom_mo_codes <- c(AMR_env$custom_mo_codes, x$mo) class(AMR_env$MO_lookup$mo) <- "character" new_df <- AMR_env$MO_lookup[0, , drop = FALSE][seq_len(NROW(x)), , drop = FALSE] rownames(new_df) <- NULL list_cols <- vapply(FUN.VALUE = logical(1), new_df, is.list) for (l in which(list_cols)) { # prevent binding NULLs in lists, replace with NA new_df[, l] <- as.list(NA_character_) } for (col in colnames(x)) { # assign new values new_df[, col] <- x[, col, drop = TRUE] } # clear previous coercions suppressMessages(mo_reset_session()) AMR_env$MO_lookup <- unique(rbind_AMR(AMR_env$MO_lookup, new_df)) class(AMR_env$MO_lookup$mo) <- c("mo", "character") if (nrow(x) <= 3) { message_("Added ", vector_and(italicise(x$fullname), quotes = FALSE), " to the internal `microorganisms` data set.") } else { message_("Added ", nr2char(nrow(x)), " records to the internal `microorganisms` data set.") } } #' @rdname add_custom_microorganisms #' @export clear_custom_microorganisms <- function() { n <- nrow(AMR_env$MO_lookup) # reset AMR_env$MO_lookup <- NULL add_MO_lookup_to_AMR_env() # clear previous coercions suppressMessages(mo_reset_session()) n2 <- nrow(AMR_env$MO_lookup) AMR_env$custom_mo_codes <- character(0) AMR_env$mo_previously_coerced <- AMR_env$mo_previously_coerced[which(AMR_env$mo_previously_coerced$mo %in% AMR_env$MO_lookup$mo), , drop = FALSE] AMR_env$mo_uncertainties <- AMR_env$mo_uncertainties[0, , drop = FALSE] message_("Cleared ", nr2char(n - n2), " custom record", ifelse(n - n2 > 1, "s", ""), " from the internal `microorganisms` data set.") } abbreviate_mo <- function(x, minlength = 5, prefix = "", hyphen_as_space = FALSE, ...) { if (hyphen_as_space == TRUE) { x <- gsub("-", " ", x, fixed = TRUE) } # keep a starting Latin ae suppressWarnings( gsub("(\u00C6|\u00E6)+", "AE", toupper( paste0(prefix, abbreviate( gsub("^ae", "\u00E6\u00E6", x, ignore.case = TRUE), minlength = minlength, use.classes = TRUE, method = "both.sides", ... )))) ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/custom_microorganisms.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Data Sets with `r format(nrow(antibiotics) + nrow(antivirals), big.mark = " ")` Antimicrobial Drugs #' #' Two data sets containing all antibiotics/antimycotics and antivirals. Use [as.ab()] or one of the [`ab_*`][ab_property()] functions to retrieve values from the [antibiotics] data set. Three identifiers are included in this data set: an antibiotic ID (`ab`, primarily used in this package) as defined by WHONET/EARS-Net, an ATC code (`atc`) as defined by the WHO, and a Compound ID (`cid`) as found in PubChem. Other properties in this data set are derived from one or more of these codes. Note that some drugs have multiple ATC codes. #' @format #' ### For the [antibiotics] data set: a [tibble][tibble::tibble] with `r nrow(antibiotics)` observations and `r ncol(antibiotics)` variables: #' - `ab`\cr Antibiotic ID as used in this package (such as `AMC`), using the official EARS-Net (European Antimicrobial Resistance Surveillance Network) codes where available. *This is a unique identifier.* #' - `cid`\cr Compound ID as found in PubChem. *This is a unique identifier.* #' - `name`\cr Official name as used by WHONET/EARS-Net or the WHO. *This is a unique identifier.* #' - `group`\cr A short and concise group name, based on WHONET and WHOCC definitions #' - `atc`\cr ATC codes (Anatomical Therapeutic Chemical) as defined by the WHOCC, like `J01CR02` #' - `atc_group1`\cr Official pharmacological subgroup (3rd level ATC code) as defined by the WHOCC, like `"Macrolides, lincosamides and streptogramins"` #' - `atc_group2`\cr Official chemical subgroup (4th level ATC code) as defined by the WHOCC, like `"Macrolides"` #' - `abbr`\cr List of abbreviations as used in many countries, also for antibiotic susceptibility testing (AST) #' - `synonyms`\cr Synonyms (often trade names) of a drug, as found in PubChem based on their compound ID #' - `oral_ddd`\cr Defined Daily Dose (DDD), oral treatment, currently available for `r sum(!is.na(antibiotics$oral_ddd))` drugs #' - `oral_units`\cr Units of `oral_ddd` #' - `iv_ddd`\cr Defined Daily Dose (DDD), parenteral (intravenous) treatment, currently available for `r sum(!is.na(antibiotics$iv_ddd))` drugs #' - `iv_units`\cr Units of `iv_ddd` #' - `loinc`\cr All codes associated with the name of the antimicrobial drug from `r TAXONOMY_VERSION$LOINC$citation` Use [ab_loinc()] to retrieve them quickly, see [ab_property()]. #' #' ### For the [antivirals] data set: a [tibble][tibble::tibble] with `r nrow(antivirals)` observations and `r ncol(antivirals)` variables: #' - `av`\cr Antiviral ID as used in this package (such as `ACI`), using the official EARS-Net (European Antimicrobial Resistance Surveillance Network) codes where available. *This is a unique identifier.* Combinations are codes that contain a `+` to indicate this, such as `ATA+COBI` for atazanavir/cobicistat. #' - `name`\cr Official name as used by WHONET/EARS-Net or the WHO. *This is a unique identifier.* #' - `atc`\cr ATC codes (Anatomical Therapeutic Chemical) as defined by the WHOCC #' - `cid`\cr Compound ID as found in PubChem. *This is a unique identifier.* #' - `atc_group`\cr Official pharmacological subgroup (3rd level ATC code) as defined by the WHOCC #' - `synonyms`\cr Synonyms (often trade names) of a drug, as found in PubChem based on their compound ID #' - `oral_ddd`\cr Defined Daily Dose (DDD), oral treatment #' - `oral_units`\cr Units of `oral_ddd` #' - `iv_ddd`\cr Defined Daily Dose (DDD), parenteral treatment #' - `iv_units`\cr Units of `iv_ddd` #' - `loinc`\cr All codes associated with the name of the antiviral drug from `r TAXONOMY_VERSION$LOINC$citation` Use [av_loinc()] to retrieve them quickly, see [av_property()]. #' @details Properties that are based on an ATC code are only available when an ATC is available. These properties are: `atc_group1`, `atc_group2`, `oral_ddd`, `oral_units`, `iv_ddd` and `iv_units`. #' #' Synonyms (i.e. trade names) were derived from the PubChem Compound ID (column `cid`) and consequently only available where a CID is available. #' #' ### Direct download #' Like all data sets in this package, these data sets are publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @source #' #' * World Health Organization (WHO) Collaborating Centre for Drug Statistics Methodology (WHOCC): <https://www.whocc.no/atc_ddd_index/> #' #' * `r TAXONOMY_VERSION$LOINC$citation` Accessed from <`r TAXONOMY_VERSION$LOINC$url`> on `r documentation_date(TAXONOMY_VERSION$LOINC$accessed_date)`. #' #' * European Commission Public Health PHARMACEUTICALS - COMMUNITY REGISTER: <https://ec.europa.eu/health/documents/community-register/html/reg_hum_atc.htm> #' @inheritSection WHOCC WHOCC #' @seealso [microorganisms], [intrinsic_resistant] #' @examples #' antibiotics #' antivirals "antibiotics" #' @rdname antibiotics "antivirals" #' Data Set with `r format(nrow(microorganisms), big.mark = " ")` Microorganisms #' #' A data set containing the full microbial taxonomy (**last updated: `r documentation_date(max(TAXONOMY_VERSION$GBIF$accessed_date, TAXONOMY_VERSION$LPSN$accessed_date))`**) of `r nr2char(length(unique(microorganisms$kingdom[!microorganisms$kingdom %like% "unknown"])))` kingdoms from the List of Prokaryotic names with Standing in Nomenclature (LPSN) and the Global Biodiversity Information Facility (GBIF). This data set is the backbone of this `AMR` package. MO codes can be looked up using [as.mo()]. #' @format A [tibble][tibble::tibble] with `r format(nrow(microorganisms), big.mark = " ")` observations and `r ncol(microorganisms)` variables: #' - `mo`\cr ID of microorganism as used by this package. *This is a unique identifier.* #' - `fullname`\cr Full name, like `"Escherichia coli"`. For the taxonomic ranks genus, species and subspecies, this is the 'pasted' text of genus, species, and subspecies. For all taxonomic ranks higher than genus, this is the name of the taxon. *This is a unique identifier.* #' - `status` \cr Status of the taxon, either `r vector_or(microorganisms$status)` #' - `kingdom`, `phylum`, `class`, `order`, `family`, `genus`, `species`, `subspecies`\cr Taxonomic rank of the microorganism #' - `rank`\cr Text of the taxonomic rank of the microorganism, such as `"species"` or `"genus"` #' - `ref`\cr Author(s) and year of related scientific publication. This contains only the *first surname* and year of the *latest* authors, e.g. "Wallis *et al.* 2006 *emend.* Smith and Jones 2018" becomes "Smith *et al.*, 2018". This field is directly retrieved from the source specified in the column `source`. Moreover, accents were removed to comply with CRAN that only allows ASCII characters. #' - `lpsn`\cr Identifier ('Record number') of the List of Prokaryotic names with Standing in Nomenclature (LPSN). This will be the first/highest LPSN identifier to keep one identifier per row. For example, *Acetobacter ascendens* has LPSN Record number 7864 and 11011. Only the first is available in the `microorganisms` data set. #' - `oxygen_tolerance` \cr Oxygen tolerance, either `r vector_or(microorganisms$oxygen_tolerance)`. These data were retrieved from BacDive (see *Source*). Items that contain "likely" are missing from BacDive and were extrapolated from other species within the same genus to guess the oxygen tolerance. Currently `r round(length(microorganisms$oxygen_tolerance[which(!is.na(microorganisms$oxygen_tolerance))]) / nrow(microorganisms[which(microorganisms$kingdom == "Bacteria"), ]) * 100, 1)`% of all `r format_included_data_number(nrow(microorganisms[which(microorganisms$kingdom == "Bacteria"), ]))` bacteria in the data set contain an oxygen tolerance. #' - `lpsn_parent`\cr LPSN identifier of the parent taxon #' - `lpsn_renamed_to`\cr LPSN identifier of the currently valid taxon #' - `gbif`\cr Identifier ('taxonID') of the Global Biodiversity Information Facility (GBIF) #' - `gbif_parent`\cr GBIF identifier of the parent taxon #' - `gbif_renamed_to`\cr GBIF identifier of the currently valid taxon #' - `source`\cr Either `r vector_or(microorganisms$source)` (see *Source*) #' - `prevalence`\cr Prevalence of the microorganism according to Bartlett *et al.* (2022, \doi{10.1099/mic.0.001269}), see [mo_matching_score()] for the full explanation #' - `snomed`\cr Systematized Nomenclature of Medicine (SNOMED) code of the microorganism, version of `r documentation_date(TAXONOMY_VERSION$SNOMED$accessed_date)` (see *Source*). Use [mo_snomed()] to retrieve it quickly, see [mo_property()]. #' @details #' Please note that entries are only based on the List of Prokaryotic names with Standing in Nomenclature (LPSN) and the Global Biodiversity Information Facility (GBIF) (see below). Since these sources incorporate entries based on (recent) publications in the International Journal of Systematic and Evolutionary Microbiology (IJSEM), it can happen that the year of publication is sometimes later than one might expect. #' #' For example, *Staphylococcus pettenkoferi* was described for the first time in Diagnostic Microbiology and Infectious Disease in 2002 (\doi{10.1016/s0732-8893(02)00399-1}), but it was not before 2007 that a publication in IJSEM followed (\doi{10.1099/ijs.0.64381-0}). Consequently, the `AMR` package returns 2007 for `mo_year("S. pettenkoferi")`. #' #' @section Included Taxa: #' Included taxonomic data are: #' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom %in% c("Archeae", "Bacteria")), , drop = FALSE])` (sub)species from the kingdoms of Archaea and Bacteria #' - `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Fungi"), , drop = FALSE])` (sub)species from the kingdom of Fungi. The kingdom of Fungi is a very large taxon with almost 300,000 different (sub)species, of which most are not microbial (but rather macroscopic, like mushrooms). Because of this, not all fungi fit the scope of this package. Only relevant fungi are covered (such as all species of *Aspergillus*, *Candida*, *Cryptococcus*, *Histoplasma*, *Pneumocystis*, *Saccharomyces* and *Trichophyton*). #' - `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Protozoa"), , drop = FALSE])` (sub)species from the kingdom of Protozoa #' - `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Animalia"), , drop = FALSE])` (sub)species from `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Animalia"), "genus", drop = TRUE])` other relevant genera from the kingdom of Animalia (such as *Strongyloides* and *Taenia*) #' - All `r format_included_data_number(microorganisms[which(microorganisms$status != "accepted"), , drop = FALSE])` previously accepted names of all included (sub)species (these were taxonomically renamed) #' - The complete taxonomic tree of all included (sub)species: from kingdom to subspecies #' - The identifier of the parent taxons #' - The year and first author of the related scientific publication #' #' ### Manual additions #' For convenience, some entries were added manually: #' #' - `r format_included_data_number(microorganisms[which(microorganisms$source == "manually added" & microorganisms$genus == "Salmonella"), , drop = FALSE])` entries of *Salmonella*, such as the city-like serovars and groups A to H #' - `r format_included_data_number(length(which(microorganisms$rank == "species group")))` species groups (such as the beta-haemolytic *Streptococcus* groups A to K, coagulase-negative *Staphylococcus* (CoNS), *Mycobacterium tuberculosis* complex, etc.), of which the group compositions are stored in the [microorganisms.groups] data set #' - 1 entry of *Blastocystis* (*B. hominis*), although it officially does not exist (Noel *et al.* 2005, PMID 15634993) #' - 1 entry of *Moraxella* (*M. catarrhalis*), which was formally named *Branhamella catarrhalis* (Catlin, 1970) though this change was never accepted within the field of clinical microbiology #' - 8 other 'undefined' entries (unknown, unknown Gram-negatives, unknown Gram-positives, unknown yeast, unknown fungus, and unknown anaerobic Gram-pos/Gram-neg bacteria) #' #' The syntax used to transform the original data to a cleansed \R format, can be found here: <https://github.com/msberends/AMR/blob/main/data-raw/reproduction_of_microorganisms.R>. #' #' ### Direct download #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @section About the Records from LPSN (see *Source*): #' LPSN is the main source for bacteriological taxonomy of this `AMR` package. #' #' The List of Prokaryotic names with Standing in Nomenclature (LPSN) provides comprehensive information on the nomenclature of prokaryotes. LPSN is a free to use service founded by Jean P. Euzeby in 1997 and later on maintained by Aidan C. Parte. #' @source #' * `r TAXONOMY_VERSION$LPSN$citation` Accessed from <`r TAXONOMY_VERSION$LPSN$url`> on `r documentation_date(TAXONOMY_VERSION$LPSN$accessed_date)`. #' #' * `r TAXONOMY_VERSION$GBIF$citation` Accessed from <`r TAXONOMY_VERSION$GBIF$url`> on `r documentation_date(TAXONOMY_VERSION$GBIF$accessed_date)`. #' #' * `r TAXONOMY_VERSION$BacDive$citation` Accessed from <`r TAXONOMY_VERSION$BacDive$url`> on `r documentation_date(TAXONOMY_VERSION$BacDive$accessed_date)`. #' #' * `r TAXONOMY_VERSION$SNOMED$citation` URL: <`r TAXONOMY_VERSION$SNOMED$url`> #' #' * Grimont *et al.* (2007). Antigenic Formulae of the Salmonella Serovars, 9th Edition. WHO Collaborating Centre for Reference and Research on *Salmonella* (WHOCC-SALM). #' #' * Bartlett *et al.* (2022). **A comprehensive list of bacterial pathogens infecting humans** *Microbiology* 168:001269; \doi{10.1099/mic.0.001269} #' @seealso [as.mo()], [mo_property()], [microorganisms.groups], [microorganisms.codes], [intrinsic_resistant] #' @examples #' microorganisms "microorganisms" #' Data Set with `r format(nrow(microorganisms.codes), big.mark = " ")` Common Microorganism Codes #' #' A data set containing commonly used codes for microorganisms, from laboratory systems and [WHONET](https://whonet.org). Define your own with [set_mo_source()]. They will all be searched when using [as.mo()] and consequently all the [`mo_*`][mo_property()] functions. #' @format A [tibble][tibble::tibble] with `r format(nrow(microorganisms.codes), big.mark = " ")` observations and `r ncol(microorganisms.codes)` variables: #' - `code`\cr Commonly used code of a microorganism. *This is a unique identifier.* #' - `mo`\cr ID of the microorganism in the [microorganisms] data set #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @seealso [as.mo()] [microorganisms] #' @examples #' microorganisms.codes #' #' # 'ECO' or 'eco' is the WHONET code for E. coli: #' microorganisms.codes[microorganisms.codes$code == "ECO", ] #' #' # and therefore, 'eco' will be understood as E. coli in this package: #' mo_info("eco") #' #' # works for all AMR functions: #' mo_is_intrinsic_resistant("eco", ab = "vancomycin") "microorganisms.codes" #' Data Set with `r format(nrow(microorganisms.groups), big.mark = " ")` Microorganisms In Species Groups #' #' A data set containing species groups and microbiological complexes, which are used in [the clinical breakpoints table][clinical_breakpoints]. #' @format A [tibble][tibble::tibble] with `r format(nrow(microorganisms.groups), big.mark = " ")` observations and `r ncol(microorganisms.groups)` variables: #' - `mo_group`\cr ID of the species group / microbiological complex #' - `mo`\cr ID of the microorganism belonging in the species group / microbiological complex #' - `mo_group_name`\cr Name of the species group / microbiological complex, as retrieved with [mo_name()] #' - `mo_name`\cr Name of the microorganism belonging in the species group / microbiological complex, as retrieved with [mo_name()] #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @seealso [as.mo()] [microorganisms] #' @examples #' microorganisms.groups #' #' # these are all species in the Bacteroides fragilis group, as per WHONET: #' microorganisms.groups[microorganisms.groups$mo_group == "B_BCTRD_FRGL-C", ] "microorganisms.groups" #' Data Set with `r format(nrow(example_isolates), big.mark = " ")` Example Isolates #' #' A data set containing `r format(nrow(example_isolates), big.mark = " ")` microbial isolates with their full antibiograms. This data set contains randomised fictitious data, but reflects reality and can be used to practise AMR data analysis. For examples, please read [the tutorial on our website](https://msberends.github.io/AMR/articles/AMR.html). #' @format A [tibble][tibble::tibble] with `r format(nrow(example_isolates), big.mark = " ")` observations and `r ncol(example_isolates)` variables: #' - `date`\cr Date of receipt at the laboratory #' - `patient`\cr ID of the patient #' - `age`\cr Age of the patient #' - `gender`\cr Gender of the patient, either `r vector_or(example_isolates$gender)` #' - `ward`\cr Ward type where the patient was admitted, either `r vector_or(example_isolates$ward)` #' - `mo`\cr ID of microorganism created with [as.mo()], see also the [microorganisms] data set #' - `PEN:RIF`\cr `r sum(vapply(FUN.VALUE = logical(1), example_isolates, is.sir))` different antibiotics with class [`sir`] (see [as.sir()]); these column names occur in the [antibiotics] data set and can be translated with [set_ab_names()] or [ab_name()] #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @examples #' example_isolates "example_isolates" #' Data Set with Unclean Data #' #' A data set containing `r format(nrow(example_isolates_unclean), big.mark = " ")` microbial isolates that are not cleaned up and consequently not ready for AMR data analysis. This data set can be used for practice. #' @format A [tibble][tibble::tibble] with `r format(nrow(example_isolates_unclean), big.mark = " ")` observations and `r ncol(example_isolates_unclean)` variables: #' - `patient_id`\cr ID of the patient #' - `date`\cr date of receipt at the laboratory #' - `hospital`\cr ID of the hospital, from A to C #' - `bacteria`\cr info about microorganism that can be transformed with [as.mo()], see also [microorganisms] #' - `AMX:GEN`\cr 4 different antibiotics that have to be transformed with [as.sir()] #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @examples #' example_isolates_unclean "example_isolates_unclean" #' Data Set with `r format(nrow(WHONET), big.mark = " ")` Isolates - WHONET Example #' #' This example data set has the exact same structure as an export file from WHONET. Such files can be used with this package, as this example data set shows. The antibiotic results are from our [example_isolates] data set. All patient names were created using online surname generators and are only in place for practice purposes. #' @format A [tibble][tibble::tibble] with `r format(nrow(WHONET), big.mark = " ")` observations and `r ncol(WHONET)` variables: #' - `Identification number`\cr ID of the sample #' - `Specimen number`\cr ID of the specimen #' - `Organism`\cr Name of the microorganism. Before analysis, you should transform this to a valid microbial class, using [as.mo()]. #' - `Country`\cr Country of origin #' - `Laboratory`\cr Name of laboratory #' - `Last name`\cr Fictitious last name of patient #' - `First name`\cr Fictitious initial of patient #' - `Sex`\cr Fictitious gender of patient #' - `Age`\cr Fictitious age of patient #' - `Age category`\cr Age group, can also be looked up using [age_groups()] #' - `Date of admission`\cr [Date] of hospital admission #' - `Specimen date`\cr [Date] when specimen was received at laboratory #' - `Specimen type`\cr Specimen type or group #' - `Specimen type (Numeric)`\cr Translation of `"Specimen type"` #' - `Reason`\cr Reason of request with Differential Diagnosis #' - `Isolate number`\cr ID of isolate #' - `Organism type`\cr Type of microorganism, can also be looked up using [mo_type()] #' - `Serotype`\cr Serotype of microorganism #' - `Beta-lactamase`\cr Microorganism produces beta-lactamase? #' - `ESBL`\cr Microorganism produces extended spectrum beta-lactamase? #' - `Carbapenemase`\cr Microorganism produces carbapenemase? #' - `MRSA screening test`\cr Microorganism is possible MRSA? #' - `Inducible clindamycin resistance`\cr Clindamycin can be induced? #' - `Comment`\cr Other comments #' - `Date of data entry`\cr [Date] this data was entered in WHONET #' - `AMP_ND10:CIP_EE`\cr `r sum(vapply(FUN.VALUE = logical(1), WHONET, is.sir))` different antibiotics. You can lookup the abbreviations in the [antibiotics] data set, or use e.g. [`ab_name("AMP")`][ab_name()] to get the official name immediately. Before analysis, you should transform this to a valid antibiotic class, using [as.sir()]. #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @examples #' WHONET "WHONET" #' Data Set with Clinical Breakpoints for SIR Interpretation #' #' Data set containing clinical breakpoints to interpret MIC and disk diffusion to SIR values, according to international guidelines. Currently implemented guidelines are EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "CLSI")$guideline)))`). Use [as.sir()] to transform MICs or disks measurements to SIR values. #' @format A [tibble][tibble::tibble] with `r format(nrow(clinical_breakpoints), big.mark = " ")` observations and `r ncol(clinical_breakpoints)` variables: #' - `guideline`\cr Name of the guideline #' - `type`\cr Breakpoint type, either `r vector_or(clinical_breakpoints$type)` #' - `method`\cr Testing method, either `r vector_or(clinical_breakpoints$method)` #' - `site`\cr Body site for which the breakpoint must be applied, e.g. "Oral" or "Respiratory" #' - `mo`\cr Microbial ID, see [as.mo()] #' - `rank_index`\cr Taxonomic rank index of `mo` from 1 (subspecies/infraspecies) to 5 (unknown microorganism) #' - `ab`\cr Antibiotic code as used by this package, EARS-Net and WHONET, see [as.ab()] #' - `ref_tbl`\cr Info about where the guideline rule can be found #' - `disk_dose`\cr Dose of the used disk diffusion method #' - `breakpoint_S`\cr Lowest MIC value or highest number of millimetres that leads to "S" #' - `breakpoint_R`\cr Highest MIC value or lowest number of millimetres that leads to "R" #' - `uti`\cr A [logical] value (`TRUE`/`FALSE`) to indicate whether the rule applies to a urinary tract infection (UTI) #' @details #' ### Different types of breakpoints #' Supported types of breakpoints are `r vector_and(clinical_breakpoints$type, quote = FALSE)`. ECOFF (Epidemiological cut-off) values are used in antimicrobial susceptibility testing to differentiate between wild-type and non-wild-type strains of bacteria or fungi. #' #' The default is `"human"`, which can also be set with the [package option][AMR-options] [`AMR_breakpoint_type`][AMR-options]. Use [`as.sir(..., breakpoint_type = ...)`][as.sir()] to interpret raw data using a specific breakpoint type, e.g. `as.sir(..., breakpoint_type = "ECOFF")` to use ECOFFs. #' #' ### Imported from WHONET #' Clinical breakpoints in this package were validated through and imported from [WHONET](https://whonet.org), a free desktop Windows application developed and supported by the WHO Collaborating Centre for Surveillance of Antimicrobial Resistance. More can be read on [their website](https://whonet.org). The developers of WHONET and this `AMR` package have been in contact about sharing their work. We highly appreciate their development on the WHONET software. #' #' ### Response from CLSI and EUCAST #' The CEO of CLSI and the chairman of EUCAST have endorsed the work and public use of this `AMR` package (and consequently the use of their breakpoints) in June 2023, when future development of distributing clinical breakpoints was discussed in a meeting between CLSI, EUCAST, the WHO, and developers of WHONET and the `AMR` package. #' #' ### Download #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). They allow for machine reading EUCAST and CLSI guidelines, which is almost impossible with the MS Excel and PDF files distributed by EUCAST and CLSI, though initiatives have started to overcome these burdens. #' #' **NOTE:** this `AMR` package (and the WHONET software as well) contains internal methods to apply the guidelines, which is rather complex. For example, some breakpoints must be applied on certain species groups (which are in case of this package available through the [microorganisms.groups] data set). It is important that this is considered when using the breakpoints for own use. #' @seealso [intrinsic_resistant] #' @examples #' clinical_breakpoints "clinical_breakpoints" #' Data Set with Bacterial Intrinsic Resistance #' #' Data set containing defined intrinsic resistance by EUCAST of all bug-drug combinations. #' @format A [tibble][tibble::tibble] with `r format(nrow(intrinsic_resistant), big.mark = " ")` observations and `r ncol(intrinsic_resistant)` variables: #' - `mo`\cr Microorganism ID #' - `ab`\cr Antibiotic ID #' @details #' This data set is based on `r format_eucast_version_nr(3.3)`. #' #' ### Direct download #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' #' They **allow for machine reading EUCAST and CLSI guidelines**, which is almost impossible with the MS Excel and PDF files distributed by EUCAST and CLSI. #' @examples #' intrinsic_resistant "intrinsic_resistant" #' Data Set with Treatment Dosages as Defined by EUCAST #' #' EUCAST breakpoints used in this package are based on the dosages in this data set. They can be retrieved with [eucast_dosage()]. #' @format A [tibble][tibble::tibble] with `r format(nrow(dosage), big.mark = " ")` observations and `r ncol(dosage)` variables: #' - `ab`\cr Antibiotic ID as used in this package (such as `AMC`), using the official EARS-Net (European Antimicrobial Resistance Surveillance Network) codes where available #' - `name`\cr Official name of the antimicrobial drug as used by WHONET/EARS-Net or the WHO #' - `type`\cr Type of the dosage, either `r vector_or(dosage$type)` #' - `dose`\cr Dose, such as "2 g" or "25 mg/kg" #' - `dose_times`\cr Number of times a dose must be administered #' - `administration`\cr Route of administration, either `r vector_or(dosage$administration)` #' - `notes`\cr Additional dosage notes #' - `original_txt`\cr Original text in the PDF file of EUCAST #' - `eucast_version`\cr Version number of the EUCAST Clinical Breakpoints guideline to which these dosages apply, either `r vector_or(dosage$eucast_version, quotes = FALSE, sort = TRUE, reverse = TRUE)` #' @details #' Like all data sets in this package, this data set is publicly available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. Please visit [our website for the download links](https://msberends.github.io/AMR/articles/datasets.html). The actual files are of course available on [our GitHub repository](https://github.com/msberends/AMR/tree/main/data-raw). #' @examples #' dosage "dosage"
/scratch/gouwar.j/cran-all/cranData/AMR/R/data.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Transform Input to Disk Diffusion Diameters #' #' This transforms a vector to a new class [`disk`], which is a disk diffusion growth zone size (around an antibiotic disk) in millimetres between 6 and 50. #' @rdname as.disk #' @param x vector #' @param na.rm a [logical] indicating whether missing values should be removed #' @details Interpret disk values as SIR values with [as.sir()]. It supports guidelines from EUCAST and CLSI. #' #' Disk diffusion growth zone sizes must be between 6 and 50 millimetres. Values higher than 50 but lower than 100 will be maximised to 50. All others input values outside the 6-50 range will return `NA`. #' @return An [integer] with additional class [`disk`] #' @aliases disk #' @export #' @seealso [as.sir()] #' @examples #' # transform existing disk zones to the `disk` class (using base R) #' df <- data.frame( #' microorganism = "Escherichia coli", #' AMP = 20, #' CIP = 14, #' GEN = 18, #' TOB = 16 #' ) #' df[, 2:5] <- lapply(df[, 2:5], as.disk) #' str(df) #' #' \donttest{ #' # transforming is easier with dplyr: #' if (require("dplyr")) { #' df %>% mutate(across(AMP:TOB, as.disk)) #' } #' } #' #' # interpret disk values, see ?as.sir #' as.sir( #' x = as.disk(18), #' mo = "Strep pneu", # `mo` will be coerced with as.mo() #' ab = "ampicillin", # and `ab` with as.ab() #' guideline = "EUCAST" #' ) #' #' # interpret whole data set, pretend to be all from urinary tract infections: #' as.sir(df, uti = TRUE) as.disk <- function(x, na.rm = FALSE) { meet_criteria(x, allow_NA = TRUE) meet_criteria(na.rm, allow_class = "logical", has_length = 1) if (!is.disk(x)) { x <- unlist(x) if (isTRUE(na.rm)) { x <- x[!is.na(x)] } x[trimws2(x) == ""] <- NA x.bak <- x na_before <- length(x[is.na(x)]) # heavily based on cleaner::clean_double(): clean_double2 <- function(x, remove = "[^0-9.,-]", fixed = FALSE) { x <- gsub(",", ".", x, fixed = TRUE) # remove ending dot/comma x <- gsub("[,.]$", "", x) # only keep last dot/comma reverse <- function(x) vapply(FUN.VALUE = character(1), lapply(strsplit(x, NULL), rev), paste, collapse = "") x <- sub("{{dot}}", ".", gsub(".", "", reverse(sub(".", "}}tod{{", reverse(x), fixed = TRUE )), fixed = TRUE ), fixed = TRUE ) x_clean <- gsub(remove, "", x, ignore.case = TRUE, fixed = fixed) # remove everything that is not a number or dot as.double(gsub("[^0-9.]+", "", x_clean)) } # round up and make it an integer x <- as.integer(ceiling(clean_double2(x))) # disks can never be less than 6 mm (size of smallest disk) or more than 50 mm x[x < 6 | x > 99] <- NA_integer_ x[x > 50] <- 50L na_after <- length(x[is.na(x)]) if (na_before != na_after) { list_missing <- x.bak[is.na(x) & !is.na(x.bak)] %pm>% unique() %pm>% sort() %pm>% vector_and(quotes = TRUE) cur_col <- get_current_column() warning_("in `as.disk()`: ", na_after - na_before, " result", ifelse(na_after - na_before > 1, "s", ""), ifelse(is.null(cur_col), "", paste0(" in column '", cur_col, "'")), " truncated (", round(((na_after - na_before) / length(x)) * 100), "%) that were invalid disk zones: ", list_missing, call = FALSE ) } } set_clean_class(as.integer(x), new_class = c("disk", "integer") ) } all_valid_disks <- function(x) { if (!inherits(x, c("disk", "character", "numeric", "integer"))) { return(FALSE) } x_disk <- tryCatch(suppressWarnings(as.disk(x[!is.na(x)])), error = function(e) NA ) !anyNA(x_disk) && !all(is.na(x)) } #' @rdname as.disk #' @details `NA_disk_` is a missing value of the new `disk` class. #' @export NA_disk_ <- set_clean_class(as.integer(NA_real_), new_class = c("disk", "integer") ) #' @rdname as.disk #' @export is.disk <- function(x) { inherits(x, "disk") } # will be exported using s3_register() in R/zzz.R pillar_shaft.disk <- function(x, ...) { out <- trimws(format(x)) out[is.na(x)] <- font_na(NA) create_pillar_column(out, align = "right", width = 2) } # will be exported using s3_register() in R/zzz.R type_sum.disk <- function(x, ...) { "disk" } #' @method print disk #' @export #' @noRd print.disk <- function(x, ...) { cat("Class 'disk'\n") print(as.integer(x), quote = FALSE) } #' @method [ disk #' @export #' @noRd "[.disk" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [[ disk #' @export #' @noRd "[[.disk" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [<- disk #' @export #' @noRd "[<-.disk" <- function(i, j, ..., value) { value <- as.disk(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method [[<- disk #' @export #' @noRd "[[<-.disk" <- function(i, j, ..., value) { value <- as.disk(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method c disk #' @export #' @noRd c.disk <- function(...) { as.disk(unlist(lapply(list(...), as.character))) } #' @method unique disk #' @export #' @noRd unique.disk <- function(x, incomparables = FALSE, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method rep disk #' @export #' @noRd rep.disk <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } # will be exported using s3_register() in R/zzz.R get_skimmers.disk <- function(column) { skimr::sfl( skim_type = "disk", min = ~ min(as.double(.), na.rm = TRUE), max = ~ max(as.double(.), na.rm = TRUE), median = ~ stats::median(as.double(.), na.rm = TRUE), n_unique = ~ length(unique(stats::na.omit(.))), hist = ~ skimr::inline_hist(stats::na.omit(as.double(.))) ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/disk.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # # ====================================================== # # || Change the EUCAST version numbers in R/globals.R || # # ====================================================== # format_eucast_version_nr <- function(version, markdown = TRUE) { # for documentation - adds title, version number, year and url in markdown language lst <- c(EUCAST_VERSION_BREAKPOINTS, EUCAST_VERSION_EXPERT_RULES) version <- format(unique(version), nsmall = 1) txt <- character(0) for (i in seq_len(length(version))) { v <- version[i] if (markdown == TRUE) { txt <- c(txt, paste0( "[", lst[[v]]$title, " ", lst[[v]]$version_txt, "](", lst[[v]]$url, ")", " (", lst[[v]]$year, ")" )) } else { txt <- c(txt, paste0( lst[[version]]$title, " ", lst[[v]]$version_txt, " (", lst[[v]]$year, ")" )) } } vector_and(txt, quotes = FALSE) } #' Apply EUCAST Rules #' #' @description #' Apply rules for clinical breakpoints and intrinsic resistance as defined by the European Committee on Antimicrobial Susceptibility Testing (EUCAST, <https://www.eucast.org>), see *Source*. Use [eucast_dosage()] to get a [data.frame] with advised dosages of a certain bug-drug combination, which is based on the [dosage] data set. #' #' To improve the interpretation of the antibiogram before EUCAST rules are applied, some non-EUCAST rules can applied at default, see *Details*. #' @param x a data set with antibiotic columns, such as `amox`, `AMX` and `AMC` #' @param info a [logical] to indicate whether progress should be printed to the console - the default is only print while in interactive sessions #' @param rules a [character] vector that specifies which rules should be applied. Must be one or more of `"breakpoints"`, `"expert"`, `"other"`, `"custom"`, `"all"`, and defaults to `c("breakpoints", "expert")`. The default value can be set to another value using the [package option][AMR-options] [`AMR_eucastrules`][AMR-options]: `options(AMR_eucastrules = "all")`. If using `"custom"`, be sure to fill in argument `custom_rules` too. Custom rules can be created with [custom_eucast_rules()]. #' @param verbose a [logical] to turn Verbose mode on and off (default is off). In Verbose mode, the function does not apply rules to the data, but instead returns a data set in logbook form with extensive info about which rows and columns would be effected and in which way. Using Verbose mode takes a lot more time. #' @param version_breakpoints the version number to use for the EUCAST Clinical Breakpoints guideline. Can be `r vector_or(names(EUCAST_VERSION_BREAKPOINTS), reverse = TRUE)`. #' @param version_expertrules the version number to use for the EUCAST Expert Rules and Intrinsic Resistance guideline. Can be `r vector_or(names(EUCAST_VERSION_EXPERT_RULES), reverse = TRUE)`. # @param version_resistant_phenotypes the version number to use for the EUCAST Expected Resistant Phenotypes. Can be `r vector_or(names(EUCAST_VERSION_RESISTANTPHENOTYPES), reverse = TRUE)`. #' @param ampc_cephalosporin_resistance a [character] value that should be applied to cefotaxime, ceftriaxone and ceftazidime for AmpC de-repressed cephalosporin-resistant mutants - the default is `NA`. Currently only works when `version_expertrules` is `3.2` and higher; these version of '*EUCAST Expert Rules on Enterobacterales*' state that results of cefotaxime, ceftriaxone and ceftazidime should be reported with a note, or results should be suppressed (emptied) for these three drugs. A value of `NA` (the default) for this argument will remove results for these three drugs, while e.g. a value of `"R"` will make the results for these drugs resistant. Use `NULL` or `FALSE` to not alter results for these three drugs of AmpC de-repressed cephalosporin-resistant mutants. Using `TRUE` is equal to using `"R"`. \cr For *EUCAST Expert Rules* v3.2, this rule applies to: `r vector_and(gsub("[^a-zA-Z ]+", "", unlist(strsplit(EUCAST_RULES_DF[which(EUCAST_RULES_DF$reference.version %in% c(3.2, 3.3) & EUCAST_RULES_DF$reference.rule %like% "ampc"), "this_value"][1], "|", fixed = TRUE))), quotes = "*")`. #' @param ... column name of an antibiotic, see section *Antibiotics* below #' @param ab any (vector of) text that can be coerced to a valid antibiotic drug code with [as.ab()] #' @param administration route of administration, either `r vector_or(dosage$administration)` #' @param only_sir_columns a [logical] to indicate whether only antibiotic columns must be detected that were transformed to class `sir` (see [as.sir()]) on beforehand (default is `FALSE`) #' @param custom_rules custom rules to apply, created with [custom_eucast_rules()] #' @inheritParams first_isolate #' @details #' **Note:** This function does not translate MIC values to SIR values. Use [as.sir()] for that. \cr #' **Note:** When ampicillin (AMP, J01CA01) is not available but amoxicillin (AMX, J01CA04) is, the latter will be used for all rules where there is a dependency on ampicillin. These drugs are interchangeable when it comes to expression of antimicrobial resistance. \cr #' #' The file containing all EUCAST rules is located here: <https://github.com/msberends/AMR/blob/main/data-raw/eucast_rules.tsv>. **Note:** Old taxonomic names are replaced with the current taxonomy where applicable. For example, *Ochrobactrum anthropi* was renamed to *Brucella anthropi* in 2020; the original EUCAST rules v3.1 and v3.2 did not yet contain this new taxonomic name. The `AMR` package contains the full microbial taxonomy updated until `r documentation_date(max(TAXONOMY_VERSION$GBIF$accessed_date, TAXONOMY_VERSION$LPSN$accessed_date))`, see [microorganisms]. #' #' ### Custom Rules #' #' Custom rules can be created using [custom_eucast_rules()], e.g.: #' #' ```r #' x <- custom_eucast_rules(AMC == "R" & genus == "Klebsiella" ~ aminopenicillins == "R", #' AMC == "I" & genus == "Klebsiella" ~ aminopenicillins == "I") #' #' eucast_rules(example_isolates, rules = "custom", custom_rules = x) #' ``` #' #' ### 'Other' Rules #' #' Before further processing, two non-EUCAST rules about drug combinations can be applied to improve the efficacy of the EUCAST rules, and the reliability of your data (analysis). These rules are: #' #' 1. A drug **with** enzyme inhibitor will be set to S if the same drug **without** enzyme inhibitor is S #' 2. A drug **without** enzyme inhibitor will be set to R if the same drug **with** enzyme inhibitor is R #' #' Important examples include amoxicillin and amoxicillin/clavulanic acid, and trimethoprim and trimethoprim/sulfamethoxazole. Needless to say, for these rules to work, both drugs must be available in the data set. #' #' Since these rules are not officially approved by EUCAST, they are not applied at default. To use these rules, include `"other"` to the `rules` argument, or use `eucast_rules(..., rules = "all")`. You can also set the [package option][AMR-options] [`AMR_eucastrules`][AMR-options], i.e. run `options(AMR_eucastrules = "all")`. #' @section Antibiotics: #' To define antibiotics column names, leave as it is to determine it automatically with [guess_ab_col()] or input a text (case-insensitive), or use `NULL` to skip a column (e.g. `TIC = NULL` to skip ticarcillin). Manually defined but non-existing columns will be skipped with a warning. #' #' The following antibiotics are eligible for the functions [eucast_rules()] and [mdro()]. These are shown below in the format 'name (`antimicrobial ID`, [ATC code](https://www.whocc.no/atc/structure_and_principles/))', sorted alphabetically: #' #' `r create_eucast_ab_documentation()` #' @aliases EUCAST #' @rdname eucast_rules #' @export #' @return The input of `x`, possibly with edited values of antibiotics. Or, if `verbose = TRUE`, a [data.frame] with all original and new values of the affected bug-drug combinations. #' @source #' - EUCAST Expert Rules. Version 2.0, 2012.\cr #' Leclercq et al. **EUCAST expert rules in antimicrobial susceptibility testing.** *Clin Microbiol Infect.* 2013;19(2):141-60; \doi{https://doi.org/10.1111/j.1469-0691.2011.03703.x} #' - EUCAST Expert Rules, Intrinsic Resistance and Exceptional Phenotypes Tables. Version 3.1, 2016. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/Expert_rules_intrinsic_exceptional_V3.1.pdf) #' - EUCAST Intrinsic Resistance and Unusual Phenotypes. Version 3.2, 2020. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2020/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.2_20200225.pdf) #' - EUCAST Intrinsic Resistance and Unusual Phenotypes. Version 3.3, 2021. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2021/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.3_20211018.pdf) #' - EUCAST Breakpoint tables for interpretation of MICs and zone diameters. Version 9.0, 2019. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Breakpoint_tables/v_9.0_Breakpoint_Tables.xlsx) #' - EUCAST Breakpoint tables for interpretation of MICs and zone diameters. Version 10.0, 2020. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Breakpoint_tables/v_10.0_Breakpoint_Tables.xlsx) #' - EUCAST Breakpoint tables for interpretation of MICs and zone diameters. Version 11.0, 2021. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Breakpoint_tables/v_11.0_Breakpoint_Tables.xlsx) #' - EUCAST Breakpoint tables for interpretation of MICs and zone diameters. Version 12.0, 2022. [(link)](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Breakpoint_tables/v_12.0_Breakpoint_Tables.xlsx) #' @inheritSection AMR Reference Data Publicly Available #' @examples #' \donttest{ #' a <- data.frame( #' mo = c( #' "Staphylococcus aureus", #' "Enterococcus faecalis", #' "Escherichia coli", #' "Klebsiella pneumoniae", #' "Pseudomonas aeruginosa" #' ), #' VAN = "-", # Vancomycin #' AMX = "-", # Amoxicillin #' COL = "-", # Colistin #' CAZ = "-", # Ceftazidime #' CXM = "-", # Cefuroxime #' PEN = "S", # Benzylpenicillin #' FOX = "S", # Cefoxitin #' stringsAsFactors = FALSE #' ) #' #' head(a) #' #' #' # apply EUCAST rules: some results wil be changed #' b <- eucast_rules(a) #' #' head(b) #' #' #' # do not apply EUCAST rules, but rather get a data.frame #' # containing all details about the transformations: #' c <- eucast_rules(a, verbose = TRUE) #' head(c) #' } #' #' # Dosage guidelines: #' #' eucast_dosage(c("tobra", "genta", "cipro"), "iv") #' #' eucast_dosage(c("tobra", "genta", "cipro"), "iv", version_breakpoints = 10) eucast_rules <- function(x, col_mo = NULL, info = interactive(), rules = getOption("AMR_eucastrules", default = c("breakpoints", "expert")), verbose = FALSE, version_breakpoints = 12.0, version_expertrules = 3.3, # TODO version_resistant_phenotypes = 1.2, ampc_cephalosporin_resistance = NA, only_sir_columns = FALSE, custom_rules = NULL, ...) { meet_criteria(x, allow_class = "data.frame") meet_criteria(col_mo, allow_class = "character", has_length = 1, is_in = colnames(x), allow_NULL = TRUE) meet_criteria(info, allow_class = "logical", has_length = 1) meet_criteria(rules, allow_class = "character", has_length = c(1, 2, 3, 4, 5), is_in = c("breakpoints", "expert", "other", "all", "custom")) meet_criteria(verbose, allow_class = "logical", has_length = 1) meet_criteria(version_breakpoints, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_BREAKPOINTS))) meet_criteria(version_expertrules, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_EXPERT_RULES))) # meet_criteria(version_resistant_phenotypes, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_RESISTANTPHENOTYPES))) meet_criteria(ampc_cephalosporin_resistance, allow_class = c("logical", "character", "sir"), has_length = 1, allow_NA = TRUE, allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(custom_rules, allow_class = "custom_eucast_rules", allow_NULL = TRUE) if ("only_rsi_columns" %in% names(list(...))) only_sir_columns <- list(...)$only_rsi_columns add_MO_lookup_to_AMR_env() if ("custom" %in% rules && is.null(custom_rules)) { warning_("in `eucast_rules()`: no custom rules were set with the `custom_rules` argument", immediate = TRUE ) rules <- rules[rules != "custom"] if (length(rules) == 0) { if (isTRUE(info)) { message_("No other rules were set, returning original data", add_fn = font_red, as_note = FALSE) } return(x) } } x_deparsed <- deparse(substitute(x)) if (length(x_deparsed) > 1 || any(x_deparsed %unlike% "[a-z]+")) { x_deparsed <- "your_data" } breakpoints_info <- EUCAST_VERSION_BREAKPOINTS[[which(as.double(names(EUCAST_VERSION_BREAKPOINTS)) == version_breakpoints)]] expertrules_info <- EUCAST_VERSION_EXPERT_RULES[[which(as.double(names(EUCAST_VERSION_EXPERT_RULES)) == version_expertrules)]] # resistantphenotypes_info <- EUCAST_VERSION_RESISTANTPHENOTYPES[[which(as.double(names(EUCAST_VERSION_RESISTANTPHENOTYPES)) == version_resistant_phenotypes)]] # support old setting (until AMR v1.3.0) if (missing(rules) && !is.null(getOption("AMR.eucast_rules"))) { rules <- getOption("AMR.eucast_rules") } if (interactive() && isTRUE(verbose) && isTRUE(info)) { txt <- paste0( "WARNING: In Verbose mode, the eucast_rules() function does not apply rules to the data, but instead returns a data set in logbook form with extensive info about which rows and columns would be effected and in which way.", "\n\nThis may overwrite your existing data if you use e.g.:", "\ndata <- eucast_rules(data, verbose = TRUE)\n\nDo you want to continue?" ) showQuestion <- import_fn("showQuestion", "rstudioapi", error_on_fail = FALSE) if (!is.null(showQuestion)) { q_continue <- showQuestion("Using verbose = TRUE with eucast_rules()", txt) } else { q_continue <- utils::menu(choices = c("OK", "Cancel"), graphics = FALSE, title = txt) } if (q_continue %in% c(FALSE, 2)) { message_("Cancelled, returning original data", add_fn = font_red, as_note = FALSE) return(x) } } # try to find columns based on type # -- mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = info) stop_if(is.null(col_mo), "`col_mo` must be set") } decimal.mark <- getOption("OutDec") big.mark <- ifelse(decimal.mark != ",", ",", " ") formatnr <- function(x, big = big.mark, dec = decimal.mark) { trimws(format(x, big.mark = big, decimal.mark = dec)) } warned <- FALSE warn_lacking_sir_class <- character(0) txt_ok <- function(n_added, n_changed, warned = FALSE) { if (warned == FALSE) { if (n_added + n_changed == 0) { cat(font_subtle(" (no changes)\n")) } else { # opening if (n_added > 0 && n_changed == 0) { cat(font_green(" (")) } else if (n_added == 0 && n_changed > 0) { cat(font_blue(" (")) } else { cat(font_grey(" (")) } # additions if (n_added > 0) { if (n_added == 1) { cat(font_green("1 value added")) } else { cat(font_green(formatnr(n_added), "values added")) } } # separator if (n_added > 0 && n_changed > 0) { cat(font_grey(", ")) } # changes if (n_changed > 0) { if (n_changed == 1) { cat(font_blue("1 value changed")) } else { cat(font_blue(formatnr(n_changed), "values changed")) } } # closing if (n_added > 0 && n_changed == 0) { cat(font_green(")\n")) } else if (n_added == 0 && n_changed > 0) { cat(font_blue(")\n")) } else { cat(font_grey(")\n")) } } warned <<- FALSE } } cols_ab <- get_column_abx( x = x, soft_dependencies = c( "AMC", "AMP", "AMX", "CIP", "ERY", "FOX1", "GEN", "MFX", "NAL", "NOR", "PEN", "PIP", "TCY", "TIC", "TOB" ), hard_dependencies = NULL, verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "eucast_rules", ... ) if (!"AMP" %in% names(cols_ab) && "AMX" %in% names(cols_ab)) { # ampicillin column is missing, but amoxicillin is available if (isTRUE(info)) { message_("Using column '", cols_ab[names(cols_ab) == "AMX"], "' as input for ampicillin since many EUCAST rules depend on it.") } cols_ab <- c(cols_ab, c(AMP = unname(cols_ab[names(cols_ab) == "AMX"]))) } # data preparation ---- if (isTRUE(info) && NROW(x) > 10000) { message_("Preparing data...", appendLF = FALSE, as_note = FALSE) } # Some helper functions --------------------------------------------------- get_antibiotic_names <- function(x) { x <- x %pm>% strsplit(",") %pm>% unlist() %pm>% trimws2() %pm>% vapply(FUN.VALUE = character(1), function(x) if (x %in% AMR::antibiotics$ab) ab_name(x, language = NULL, tolower = TRUE, fast_mode = TRUE) else x) %pm>% sort() %pm>% paste(collapse = ", ") x <- gsub("_", " ", x, fixed = TRUE) x <- gsub("except CAZ", paste("except", ab_name("CAZ", language = NULL, tolower = TRUE)), x, fixed = TRUE) x <- gsub("except TGC", paste("except", ab_name("TGC", language = NULL, tolower = TRUE)), x, fixed = TRUE) x <- gsub("cephalosporins (1st|2nd|3rd|4th|5th)", "cephalosporins (\\1 gen.)", x) x } format_antibiotic_names <- function(ab_names, ab_results) { ab_names <- trimws2(unlist(strsplit(ab_names, ","))) ab_results <- trimws2(unlist(strsplit(ab_results, ","))) if (length(ab_results) == 1) { if (length(ab_names) == 1) { # like FOX S x <- paste(ab_names, "is") } else if (length(ab_names) == 2) { # like PEN,FOX S x <- paste(paste0(ab_names, collapse = " and "), "are both") } else { # like PEN,FOX,GEN S (although dependency on > 2 ABx does not exist at the moment) # nolint start # x <- paste(paste0(ab_names, collapse = " and "), "are all") # nolint end } return(paste0(x, " '", ab_results, "'")) } else { if (length(ab_names) == 2) { # like PEN,FOX S,R paste0( ab_names[1], " is '", ab_results[1], "' and ", ab_names[2], " is '", ab_results[2], "'" ) } else { # like PEN,FOX,GEN S,R,R (although dependency on > 2 ABx does not exist at the moment) paste0( ab_names[1], " is '", ab_results[1], "' and ", ab_names[2], " is '", ab_results[2], "' and ", ab_names[3], " is '", ab_results[3], "'" ) } } } as.sir_no_warning <- function(x) { if (is.sir(x)) { return(x) } suppressWarnings(as.sir(x)) } # Preparing the data ------------------------------------------------------ verbose_info <- data.frame( rowid = character(0), col = character(0), mo_fullname = character(0), old = as.sir(character(0)), new = as.sir(character(0)), rule = character(0), rule_group = character(0), rule_name = character(0), rule_source = character(0), stringsAsFactors = FALSE ) old_cols <- colnames(x) old_attributes <- attributes(x) x <- as.data.frame(x, stringsAsFactors = FALSE) # no tibbles, data.tables, etc. rownames(x) <- NULL # will later be restored with old_attributes # create unique row IDs - combination of the MO and all ABx columns (so they will only run once per unique combination) x$`.rowid` <- vapply( FUN.VALUE = character(1), as.list(as.data.frame(t(x[, c(col_mo, cols_ab), drop = FALSE]), stringsAsFactors = FALSE )), function(x) { x[is.na(x)] <- "." paste0(x, collapse = "") } ) # save original table, with the new .rowid column x.bak <- x # keep only unique rows for MO and ABx x <- x %pm>% pm_arrange(`.rowid`) %pm>% # big speed gain! only analyse unique rows: pm_distinct(`.rowid`, .keep_all = TRUE) %pm>% as.data.frame(stringsAsFactors = FALSE) x[, col_mo] <- as.mo(as.character(x[, col_mo, drop = TRUE]), info = info) # rename col_mo to prevent interference with joined columns colnames(x)[colnames(x) == col_mo] <- ".col_mo" col_mo <- ".col_mo" # join to microorganisms data set x <- left_join_microorganisms(x, by = col_mo, suffix = c("_oldcols", "")) x$gramstain <- mo_gramstain(x[, col_mo, drop = TRUE], language = NULL, info = FALSE) x$genus_species <- trimws(paste(x$genus, x$species)) if (isTRUE(info) && NROW(x) > 10000) { message_(" OK.", add_fn = list(font_green, font_bold), as_note = FALSE) } if (any(x$genus == "Staphylococcus", na.rm = TRUE)) { all_staph <- AMR_env$MO_lookup[which(AMR_env$MO_lookup$genus == "Staphylococcus"), , drop = FALSE] all_staph$CNS_CPS <- suppressWarnings(mo_name(all_staph$mo, Becker = "all", language = NULL, info = FALSE)) } if (any(x$genus == "Streptococcus", na.rm = TRUE)) { all_strep <- AMR_env$MO_lookup[which(AMR_env$MO_lookup$genus == "Streptococcus"), , drop = FALSE] all_strep$Lancefield <- suppressWarnings(mo_name(all_strep$mo, Lancefield = TRUE, language = NULL, info = FALSE)) } n_added <- 0 n_changed <- 0 # Other rules: enzyme inhibitors ------------------------------------------ if (any(c("all", "other") %in% rules)) { if (isTRUE(info)) { cat("\n") cat(word_wrap( font_bold(paste0( "Rules by this AMR package (", font_red(paste0( "v", utils::packageDescription("AMR")$Version, ", ", format(as.Date(utils::packageDescription("AMR")$Date), format = "%Y") )), "), see ?eucast_rules\n" )) )) } ab_enzyme <- subset(AMR::antibiotics, name %like% "/")[, c("ab", "name"), drop = FALSE] colnames(ab_enzyme) <- c("enzyme_ab", "enzyme_name") ab_enzyme$base_name <- gsub("^([a-zA-Z0-9]+).*", "\\1", ab_enzyme$enzyme_name) ab_enzyme$base_ab <- AMR::antibiotics[match(ab_enzyme$base_name, AMR::antibiotics$name), "ab", drop = TRUE] ab_enzyme <- subset(ab_enzyme, !is.na(base_ab)) # make ampicillin and amoxicillin interchangable ampi <- subset(ab_enzyme, base_ab == "AMX") ampi$base_ab <- "AMP" ampi$base_name <- ab_name("AMP", language = NULL) amox <- subset(ab_enzyme, base_ab == "AMP") amox$base_ab <- "AMX" amox$base_name <- ab_name("AMX", language = NULL) # merge and sort ab_enzyme <- rbind_AMR(ab_enzyme, ampi, amox) ab_enzyme <- ab_enzyme[order(ab_enzyme$enzyme_name), , drop = FALSE] for (i in seq_len(nrow(ab_enzyme))) { # check if both base and base + enzyme inhibitor are part of the data set if (all(c(ab_enzyme$base_ab[i], ab_enzyme$enzyme_ab[i]) %in% names(cols_ab), na.rm = TRUE)) { col_base <- unname(cols_ab[ab_enzyme$base_ab[i]]) col_enzyme <- unname(cols_ab[ab_enzyme$enzyme_ab[i]]) # Set base to R where base + enzyme inhibitor is R ---- rule_current <- paste0( ab_enzyme$base_name[i], " ('", font_bold(col_base), "') = R if ", tolower(ab_enzyme$enzyme_name[i]), " ('", font_bold(col_enzyme), "') = R" ) if (isTRUE(info)) { cat(word_wrap(rule_current, width = getOption("width") - 30, extra_indent = 6 )) } run_changes <- edit_sir( x = x, to = "R", rule = c( rule_current, "Other rules", "", paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version) ), rows = which(as.sir_no_warning(x[, col_enzyme, drop = TRUE]) == "R"), cols = col_base, last_verbose_info = verbose_info, original_data = x.bak, warned = warned, info = info, verbose = verbose ) n_added <- n_added + run_changes$added n_changed <- n_changed + run_changes$changed verbose_info <- run_changes$verbose_info x <- run_changes$output warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn) # Print number of new changes if (isTRUE(info)) { # print only on last one of rules in this group txt_ok(n_added = n_added, n_changed = n_changed, warned = warned) # and reset counters n_added <- 0 n_changed <- 0 } # Set base + enzyme inhibitor to S where base is S ---- rule_current <- paste0( ab_enzyme$enzyme_name[i], " ('", font_bold(col_enzyme), "') = S if ", tolower(ab_enzyme$base_name[i]), " ('", font_bold(col_base), "') = S" ) if (isTRUE(info)) { cat(word_wrap(rule_current, width = getOption("width") - 30, extra_indent = 6 )) } run_changes <- edit_sir( x = x, to = "S", rule = c( rule_current, "Other rules", "", paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version) ), rows = which(as.sir_no_warning(x[, col_base, drop = TRUE]) == "S"), cols = col_enzyme, last_verbose_info = verbose_info, original_data = x.bak, warned = warned, info = info, verbose = verbose ) n_added <- n_added + run_changes$added n_changed <- n_changed + run_changes$changed verbose_info <- run_changes$verbose_info x <- run_changes$output warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn) # Print number of new changes if (isTRUE(info)) { # print only on last one of rules in this group txt_ok(n_added = n_added, n_changed = n_changed, warned = warned) # and reset counters n_added <- 0 n_changed <- 0 } } } } else { if (isTRUE(info)) { cat("\n") message_("Skipping inheritance rules defined by this AMR package, such as setting trimethoprim (TMP) = R where trimethoprim/sulfamethoxazole (SXT) = R. Add \"other\" or \"all\" to the `rules` argument to apply those rules.") } } if (!any(c("all", "custom") %in% rules) && !is.null(custom_rules)) { if (isTRUE(info)) { message_("Skipping custom EUCAST rules, since the `rules` argument does not contain \"custom\".") } custom_rules <- NULL } # Official EUCAST rules --------------------------------------------------- eucast_notification_shown <- FALSE if (!is.null(list(...)$eucast_rules_df)) { # this allows: eucast_rules(x, eucast_rules_df = AMR:::EUCAST_RULES_DF %>% filter(is.na(have_these_values))) eucast_rules_df <- list(...)$eucast_rules_df } else { # otherwise internal data file, created in data-raw/_pre_commit_hook.R eucast_rules_df <- EUCAST_RULES_DF } # filter on user-set guideline versions ---- if (any(c("all", "breakpoints") %in% rules)) { eucast_rules_df <- subset( eucast_rules_df, reference.rule_group %unlike% "breakpoint" | (reference.rule_group %like% "breakpoint" & reference.version == version_breakpoints) ) } if (any(c("all", "expert") %in% rules)) { eucast_rules_df <- subset( eucast_rules_df, reference.rule_group %unlike% "expert" | (reference.rule_group %like% "expert" & reference.version == version_expertrules) ) } # filter out AmpC de-repressed cephalosporin-resistant mutants ---- # no need to filter on version number here - the rules contain these version number, so are inherently filtered # cefotaxime, ceftriaxone, ceftazidime if (is.null(ampc_cephalosporin_resistance) || isFALSE(ampc_cephalosporin_resistance)) { eucast_rules_df <- subset( eucast_rules_df, reference.rule %unlike% "ampc" ) } else { if (isTRUE(ampc_cephalosporin_resistance)) { ampc_cephalosporin_resistance <- "R" } eucast_rules_df[which(eucast_rules_df$reference.rule %like% "ampc"), "to_value"] <- as.character(ampc_cephalosporin_resistance) } # Go over all rules and apply them ---- for (i in seq_len(nrow(eucast_rules_df))) { rule_previous <- eucast_rules_df[max(1, i - 1), "reference.rule", drop = TRUE] rule_current <- eucast_rules_df[i, "reference.rule", drop = TRUE] rule_next <- eucast_rules_df[min(nrow(eucast_rules_df), i + 1), "reference.rule", drop = TRUE] rule_group_previous <- eucast_rules_df[max(1, i - 1), "reference.rule_group", drop = TRUE] rule_group_current <- eucast_rules_df[i, "reference.rule_group", drop = TRUE] # don't apply rules if user doesn't want to apply them if (rule_group_current %like% "breakpoint" && !any(c("all", "breakpoints") %in% rules)) { next } if (rule_group_current %like% "expert" && !any(c("all", "expert") %in% rules)) { next } if (isFALSE(info) || isFALSE(verbose)) { rule_text <- "" } else { if (is.na(eucast_rules_df[i, "and_these_antibiotics", drop = TRUE])) { rule_text <- paste0("always report as '", eucast_rules_df[i, "to_value", drop = TRUE], "': ", get_antibiotic_names(eucast_rules_df[i, "then_change_these_antibiotics", drop = TRUE])) } else { rule_text <- paste0( "report as '", eucast_rules_df[i, "to_value", drop = TRUE], "' when ", format_antibiotic_names( ab_names = get_antibiotic_names(eucast_rules_df[i, "and_these_antibiotics", drop = TRUE]), ab_results = eucast_rules_df[i, "have_these_values", drop = TRUE] ), ": ", get_antibiotic_names(eucast_rules_df[i, "then_change_these_antibiotics", drop = TRUE]) ) } } if (i == 1) { rule_previous <- "" rule_group_previous <- "" } if (i == nrow(eucast_rules_df)) { rule_next <- "" } if (isTRUE(info)) { # Print EUCAST intro ------------------------------------------------------ if (rule_group_current %unlike% "other" && eucast_notification_shown == FALSE) { cat( paste0( "\n", font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n", word_wrap("Rules by the ", font_bold("European Committee on Antimicrobial Susceptibility Testing (EUCAST)")), "\n", font_blue("https://eucast.org/"), "\n" ) ) eucast_notification_shown <- TRUE } # Print rule (group) ------------------------------------------------------ if (rule_group_current != rule_group_previous) { # is new rule group, one of Breakpoints, Expert Rules and Other cat(font_bold( ifelse( rule_group_current %like% "breakpoint", paste0( "\n", word_wrap( breakpoints_info$title, " (", font_red(paste0(breakpoints_info$version_txt, ", ", breakpoints_info$year)), ")\n" ) ), ifelse( rule_group_current %like% "expert", paste0( "\n", word_wrap( expertrules_info$title, " (", font_red(paste0(expertrules_info$version_txt, ", ", expertrules_info$year)), ")\n" ) ), "" ) ) ), "\n") } # Print rule ------------------------------------------------------------- if (rule_current != rule_previous) { # is new rule within group, print its name cat(italicise_taxonomy( word_wrap(rule_current, width = getOption("width") - 30, extra_indent = 6 ), type = "ansi" )) warned <- FALSE } } # Get rule from file ------------------------------------------------------ if_mo_property <- trimws(eucast_rules_df[i, "if_mo_property", drop = TRUE]) like_is_one_of <- trimws(eucast_rules_df[i, "like.is.one_of", drop = TRUE]) mo_value <- trimws(eucast_rules_df[i, "this_value", drop = TRUE]) # be sure to comprise all coagulase-negative/-positive staphylococci when they are mentioned if (mo_value %like% "coagulase" && any(x$genus == "Staphylococcus", na.rm = TRUE)) { if (mo_value %like% "negative") { eucast_rules_df[i, "this_value"] <- paste0( "^(", paste0( all_staph[which(all_staph$CNS_CPS %like% "negative"), "fullname", drop = TRUE ], collapse = "|" ), ")$" ) } else { eucast_rules_df[i, "this_value"] <- paste0( "^(", paste0( all_staph[which(all_staph$CNS_CPS %like% "positive"), "fullname", drop = TRUE ], collapse = "|" ), ")$" ) } like_is_one_of <- "like" } # be sure to comprise all beta-haemolytic Streptococci (Lancefield groups A, B, C and G) when they are mentioned if (mo_value %like% "group [ABCG]" && any(x$genus == "Streptococcus", na.rm = TRUE)) { eucast_rules_df[i, "this_value"] <- paste0( "^(", paste0( all_strep[which(all_strep$Lancefield %like% "group [ABCG]"), "fullname", drop = TRUE ], collapse = "|" ), ")$" ) like_is_one_of <- "like" } if (like_is_one_of == "is") { # so e.g. 'Enterococcus' will turn into '^Enterococcus$' mo_value <- paste0("^", mo_value, "$") } else if (like_is_one_of == "one_of") { # so 'Clostridium, Actinomyces, ...' will turn into '^(Clostridium|Actinomyces|...)$' mo_value <- paste0( "^(", paste(trimws(unlist(strsplit(mo_value, ",", fixed = TRUE))), collapse = "|" ), ")$" ) } else if (like_is_one_of != "like") { stop("invalid value for column 'like.is.one_of'", call. = FALSE) } source_antibiotics <- eucast_rules_df[i, "and_these_antibiotics", drop = TRUE] source_value <- trimws(unlist(strsplit(eucast_rules_df[i, "have_these_values", drop = TRUE], ",", fixed = TRUE))) target_antibiotics <- eucast_rules_df[i, "then_change_these_antibiotics", drop = TRUE] target_value <- eucast_rules_df[i, "to_value", drop = TRUE] if (is.na(source_antibiotics)) { rows <- tryCatch(which(x[, if_mo_property, drop = TRUE] %like% mo_value), error = function(e) integer(0) ) } else { source_antibiotics <- get_ab_from_namespace(source_antibiotics, cols_ab) if (length(source_value) == 1 && length(source_antibiotics) > 1) { source_value <- rep(source_value, length(source_antibiotics)) } if (length(source_antibiotics) == 0) { rows <- integer(0) } else if (length(source_antibiotics) == 1) { rows <- tryCatch( which(x[, if_mo_property, drop = TRUE] %like% mo_value & as.sir_no_warning(x[, source_antibiotics[1L]]) == source_value[1L]), error = function(e) integer(0) ) } else if (length(source_antibiotics) == 2) { rows <- tryCatch( which(x[, if_mo_property, drop = TRUE] %like% mo_value & as.sir_no_warning(x[, source_antibiotics[1L]]) == source_value[1L] & as.sir_no_warning(x[, source_antibiotics[2L]]) == source_value[2L]), error = function(e) integer(0) ) # nolint start # } else if (length(source_antibiotics) == 3) { # rows <- tryCatch(which(x[, if_mo_property, drop = TRUE] %like% mo_value # & as.sir_no_warning(x[, source_antibiotics[1L]]) == source_value[1L] # & as.sir_no_warning(x[, source_antibiotics[2L]]) == source_value[2L] # & as.sir_no_warning(x[, source_antibiotics[3L]]) == source_value[3L]), # error = function(e) integer(0)) # nolint end } else { stop_("only 2 antibiotics supported for source_antibiotics") } } cols <- get_ab_from_namespace(target_antibiotics, cols_ab) # Apply rule on data ------------------------------------------------------ # this will return the unique number of changes run_changes <- edit_sir( x = x, to = target_value, rule = c( rule_text, rule_group_current, rule_current, ifelse(rule_group_current %like% "breakpoint", paste0(breakpoints_info$title, " ", breakpoints_info$version_txt, ", ", breakpoints_info$year), paste0(expertrules_info$title, " ", expertrules_info$version_txt, ", ", expertrules_info$year) ) ), rows = rows, cols = cols, last_verbose_info = verbose_info, original_data = x.bak, warned = warned, info = info, verbose = verbose ) n_added <- n_added + run_changes$added n_changed <- n_changed + run_changes$changed verbose_info <- run_changes$verbose_info x <- run_changes$output warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn) # Print number of new changes --------------------------------------------- if (isTRUE(info) && rule_next != rule_current) { # print only on last one of rules in this group txt_ok(n_added = n_added, n_changed = n_changed, warned = warned) # and reset counters n_added <- 0 n_changed <- 0 } } # end of going over all rules # Apply custom rules ---- if (!is.null(custom_rules)) { if (isTRUE(info)) { cat("\n") cat(font_bold("Custom EUCAST rules, set by user"), "\n") } for (i in seq_len(length(custom_rules))) { rule <- custom_rules[[i]] rows <- which(eval(parse(text = rule$query), envir = x)) cols <- as.character(rule$result_group) cols <- c( cols[cols %in% colnames(x)], # direct column names unname(cols_ab[names(cols_ab) %in% cols]) ) # based on previous cols_ab finding cols <- unique(cols) target_value <- as.character(rule$result_value) rule_text <- paste0( "report as '", target_value, "' when ", format_custom_query_rule(rule$query, colours = FALSE), ": ", get_antibiotic_names(cols) ) if (isTRUE(info)) { # print rule cat(italicise_taxonomy( word_wrap(format_custom_query_rule(rule$query, colours = FALSE), width = getOption("width") - 30, extra_indent = 6 ), type = "ansi" )) warned <- FALSE } run_changes <- edit_sir( x = x, to = target_value, rule = c( rule_text, "Custom EUCAST rules", paste0("Custom EUCAST rule ", i), paste0( "Object '", deparse(substitute(custom_rules)), "' consisting of ", length(custom_rules), " custom rules" ) ), rows = rows, cols = cols, last_verbose_info = verbose_info, original_data = x.bak, warned = warned, info = info, verbose = verbose ) n_added <- n_added + run_changes$added n_changed <- n_changed + run_changes$changed verbose_info <- run_changes$verbose_info x <- run_changes$output warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn) # Print number of new changes --------------------------------------------- if (isTRUE(info) && rule_next != rule_current) { # print only on last one of rules in this group txt_ok(n_added = n_added, n_changed = n_changed, warned = warned) # and reset counters n_added <- 0 n_changed <- 0 } } } # Print overview ---------------------------------------------------------- if (isTRUE(info) || isTRUE(verbose)) { verbose_info <- x.bak %pm>% pm_mutate(row = pm_row_number()) %pm>% pm_select(`.rowid`, row) %pm>% pm_right_join(verbose_info, by = c(".rowid" = "rowid") ) %pm>% pm_select(-`.rowid`) %pm>% pm_select(row, pm_everything()) %pm>% pm_filter(!is.na(new) | is.na(new) & !is.na(old)) %pm>% pm_arrange(row, rule_group, rule_name, col) rownames(verbose_info) <- NULL } if (isTRUE(info)) { if (isTRUE(verbose)) { wouldve <- "would have " } else { wouldve <- "" } cat(paste0("\n", font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n")) cat(word_wrap(paste0( "The rules ", paste0(wouldve, "affected "), font_bold( formatnr(pm_n_distinct(verbose_info$row)), "out of", formatnr(nrow(x.bak)), "rows" ), ", making a total of ", font_bold(formatnr(nrow(verbose_info)), "edits\n") ))) total_n_added <- verbose_info %pm>% pm_filter(is.na(old)) %pm>% nrow() total_n_changed <- verbose_info %pm>% pm_filter(!is.na(old)) %pm>% nrow() # print added values if (total_n_added == 0) { colour <- cat # is function } else { colour <- font_green # is function } cat(colour(paste0( "=> ", wouldve, "added ", font_bold(formatnr(verbose_info %pm>% pm_filter(is.na(old)) %pm>% nrow()), "test results"), "\n" ))) if (total_n_added > 0) { added_summary <- verbose_info %pm>% pm_filter(is.na(old)) %pm>% pm_count(new, name = "n") cat(paste(" -", paste0( formatnr(added_summary$n), " test result", ifelse(added_summary$n > 1, "s", ""), " added as ", paste0('"', added_summary$new, '"') ), collapse = "\n" )) } # print changed values if (total_n_changed == 0) { colour <- cat # is function } else { colour <- font_blue # is function } if (total_n_added + total_n_changed > 0) { cat("\n") } cat(colour(paste0( "=> ", wouldve, "changed ", font_bold(formatnr(verbose_info %pm>% pm_filter(!is.na(old)) %pm>% nrow()), "test results"), "\n" ))) if (total_n_changed > 0) { changed_summary <- verbose_info %pm>% pm_filter(!is.na(old)) %pm>% pm_mutate(new = ifelse(is.na(new), "NA", new)) %pm>% pm_count(old, new, name = "n") cat(paste(" -", paste0( formatnr(changed_summary$n), " test result", ifelse(changed_summary$n > 1, "s", ""), " changed from ", paste0('"', changed_summary$old, '"'), " to ", paste0('"', changed_summary$new, '"') ), collapse = "\n" )) cat("\n") } cat(paste0(font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n")) if (isFALSE(verbose) && total_n_added + total_n_changed > 0) { cat("\n", word_wrap("Use ", font_bold("eucast_rules(..., verbose = TRUE)"), " (on your original data) to get a data.frame with all specified edits instead."), "\n\n", sep = "") } else if (isTRUE(verbose)) { cat("\n", word_wrap("Used 'Verbose mode' (", font_bold("verbose = TRUE"), "), which returns a data.frame with all specified edits.\nUse ", font_bold("verbose = FALSE"), " to apply the rules on your data."), "\n\n", sep = "") } } if (length(warn_lacking_sir_class) > 0) { warn_lacking_sir_class <- unique(warn_lacking_sir_class) # take order from original data set warn_lacking_sir_class <- warn_lacking_sir_class[order(colnames(x.bak))] warn_lacking_sir_class <- warn_lacking_sir_class[!is.na(warn_lacking_sir_class)] warning_( "in `eucast_rules()`: not all columns with antimicrobial results are of class 'sir'. Transform them on beforehand, with e.g.:\n", " - ", x_deparsed, " %>% as.sir(", ifelse(length(warn_lacking_sir_class) == 1, warn_lacking_sir_class, paste0(warn_lacking_sir_class[1], ":", warn_lacking_sir_class[length(warn_lacking_sir_class)]) ), ")\n", " - ", x_deparsed, " %>% mutate_if(is_sir_eligible, as.sir)\n", " - ", x_deparsed, " %>% mutate(across(where(is_sir_eligible), as.sir))" ) } # Return data set --------------------------------------------------------- if (isTRUE(verbose)) { as_original_data_class(verbose_info, old_attributes$class) # will remove tibble groups } else { # x was analysed with only unique rows, so join everything together again x <- x[, c(cols_ab, ".rowid"), drop = FALSE] x.bak <- x.bak[, setdiff(colnames(x.bak), cols_ab), drop = FALSE] x.bak <- x.bak %pm>% pm_left_join(x, by = ".rowid") x.bak <- x.bak[, old_cols, drop = FALSE] # reset original attributes attributes(x.bak) <- old_attributes x.bak <- as_original_data_class(x.bak, old_class = class(x.bak)) # will remove tibble groups x.bak } } # helper function for editing the table ---- edit_sir <- function(x, to, rule, rows, cols, last_verbose_info, original_data, warned, info, verbose) { cols <- unique(cols[!is.na(cols) & !is.null(cols)]) # for Verbose Mode, keep track of all changes and return them track_changes <- list( added = 0, changed = 0, output = x, verbose_info = last_verbose_info, sir_warn = character(0) ) txt_error <- function() { if (isTRUE(info)) cat("", font_red_bg(" ERROR "), "\n\n") } txt_warning <- function() { if (warned == FALSE) { if (isTRUE(info)) cat(" ", font_orange_bg(" WARNING "), sep = "") } warned <<- TRUE } if (length(rows) > 0 && length(cols) > 0) { new_edits <- x if (any(!vapply(FUN.VALUE = logical(1), x[, cols, drop = FALSE], is.sir), na.rm = TRUE)) { track_changes$sir_warn <- cols[!vapply(FUN.VALUE = logical(1), x[, cols, drop = FALSE], is.sir)] } tryCatch( # insert into original table new_edits[rows, cols] <- to, warning = function(w) { if (w$message %like% "invalid factor level") { xyz <- vapply(FUN.VALUE = logical(1), cols, function(col) { new_edits[, col] <<- factor( x = as.character(pm_pull(new_edits, col)), levels = unique(c(to, levels(pm_pull(new_edits, col)))) ) TRUE }) suppressWarnings(new_edits[rows, cols] <<- to) warning_( "in `eucast_rules()`: value \"", to, "\" added to the factor levels of column", ifelse(length(cols) == 1, "", "s"), " ", vector_and(cols, quotes = "`", sort = FALSE), " because this value was not an existing factor level." ) txt_warning() warned <- FALSE } else { warning_("in `eucast_rules()`: ", w$message) txt_warning() } }, error = function(e) { txt_error() stop( paste0( "In row(s) ", paste(rows[seq_len(min(length(rows), 10))], collapse = ","), ifelse(length(rows) > 10, "...", ""), " while writing value '", to, "' to column(s) `", paste(cols, collapse = "`, `"), "`:\n", e$message ), call. = FALSE ) } ) track_changes$output <- new_edits if ((isTRUE(info) || isTRUE(verbose)) && !isTRUE(all.equal(x, track_changes$output))) { get_original_rows <- function(rowids) { as.integer(rownames(original_data[which(original_data$.rowid %in% rowids), , drop = FALSE])) } for (i in seq_len(length(cols))) { verbose_new <- data.frame( rowid = new_edits[rows, ".rowid", drop = TRUE], col = cols[i], mo_fullname = new_edits[rows, "fullname", drop = TRUE], old = x[rows, cols[i], drop = TRUE], new = to, rule = font_stripstyle(rule[1]), rule_group = font_stripstyle(rule[2]), rule_name = font_stripstyle(rule[3]), rule_source = font_stripstyle(rule[4]), stringsAsFactors = FALSE ) colnames(verbose_new) <- c( "rowid", "col", "mo_fullname", "old", "new", "rule", "rule_group", "rule_name", "rule_source" ) verbose_new <- verbose_new %pm>% pm_filter(old != new | is.na(old) | is.na(new) & !is.na(old)) # save changes to data set 'verbose_info' track_changes$verbose_info <- rbind_AMR( track_changes$verbose_info, verbose_new ) # count adds and changes track_changes$added <- track_changes$added + verbose_new %pm>% pm_filter(is.na(old)) %pm>% pm_pull(rowid) %pm>% get_original_rows() %pm>% length() track_changes$changed <- track_changes$changed + verbose_new %pm>% pm_filter(!is.na(old)) %pm>% pm_pull(rowid) %pm>% get_original_rows() %pm>% length() } } } return(track_changes) } #' @rdname eucast_rules #' @export eucast_dosage <- function(ab, administration = "iv", version_breakpoints = 12.0) { meet_criteria(ab, allow_class = c("character", "numeric", "integer", "factor")) meet_criteria(administration, allow_class = "character", is_in = dosage$administration[!is.na(dosage$administration)], has_length = 1) meet_criteria(version_breakpoints, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_BREAKPOINTS))) # show used version_breakpoints number once per session (AMR_env will reload every session) if (message_not_thrown_before("eucast_dosage", "v", gsub("[^0-9]", "", version_breakpoints), entire_session = TRUE)) { 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.") ) } ab <- as.ab(ab) lst <- vector("list", length = length(ab)) for (i in seq_len(length(ab))) { df <- AMR::dosage[which(AMR::dosage$ab == ab[i] & AMR::dosage$administration == administration), , drop = FALSE] lst[[i]] <- list( ab = "", name = "", standard_dosage = ifelse("standard_dosage" %in% df$type, df[which(df$type == "standard_dosage"), "original_txt", drop = TRUE], NA_character_ ), high_dosage = ifelse("high_dosage" %in% df$type, df[which(df$type == "high_dosage"), "original_txt", drop = TRUE], NA_character_ ) ) } out <- do.call(rbind_AMR, lapply(lst, as.data.frame, stringsAsFactors = FALSE)) rownames(out) <- NULL out$ab <- ab out$name <- ab_name(ab, language = NULL) if (pkg_is_available("tibble")) { import_fn("as_tibble", "tibble")(out) } else { out } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/eucast_rules.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Determine First Isolates #' #' Determine first isolates of all microorganisms of every patient per episode and (if needed) per specimen type. These functions support all four methods as summarised by Hindler *et al.* in 2007 (\doi{10.1086/511864}). To determine patient episodes not necessarily based on microorganisms, use [is_new_episode()] that also supports grouping with the `dplyr` package. #' @param x a [data.frame] containing isolates. Can be left blank for automatic determination, see *Examples*. #' @param col_date column name of the result date (or date that is was received on the lab) - the default is the first column with a date class #' @param col_patient_id column name of the unique IDs of the patients - the default is the first column that starts with 'patient' or 'patid' (case insensitive) #' @param col_mo column name of the names or codes of the microorganisms (see [as.mo()]) - the default is the first column of class [`mo`]. Values will be coerced using [as.mo()]. #' @param col_testcode column name of the test codes. Use `col_testcode = NULL` to **not** exclude certain test codes (such as test codes for screening). In that case `testcodes_exclude` will be ignored. #' @param col_specimen column name of the specimen type or group #' @param col_icu column name of the logicals (`TRUE`/`FALSE`) whether a ward or department is an Intensive Care Unit (ICU). This can also be a [logical] vector with the same length as rows in `x`. #' @param col_keyantimicrobials (only useful when `method = "phenotype-based"`) column name of the key antimicrobials to determine first isolates, see [key_antimicrobials()]. The default is the first column that starts with 'key' followed by 'ab' or 'antibiotics' or 'antimicrobials' (case insensitive). Use `col_keyantimicrobials = FALSE` to prevent this. Can also be the output of [key_antimicrobials()]. #' @param episode_days episode in days after which a genus/species combination will be determined as 'first isolate' again. The default of 365 days is based on the guideline by CLSI, see *Source*. #' @param testcodes_exclude a [character] vector with test codes that should be excluded (case-insensitive) #' @param icu_exclude a [logical] to indicate whether ICU isolates should be excluded (rows with value `TRUE` in the column set with `col_icu`) #' @param specimen_group value in the column set with `col_specimen` to filter on #' @param type type to determine weighed isolates; can be `"keyantimicrobials"` or `"points"`, see *Details* #' @param method the method to apply, either `"phenotype-based"`, `"episode-based"`, `"patient-based"` or `"isolate-based"` (can be abbreviated), see *Details*. The default is `"phenotype-based"` if antimicrobial test results are present in the data, and `"episode-based"` otherwise. #' @param ignore_I [logical] to indicate whether antibiotic interpretations with `"I"` will be ignored when `type = "keyantimicrobials"`, see *Details* #' @param points_threshold minimum number of points to require before differences in the antibiogram will lead to inclusion of an isolate when `type = "points"`, see *Details* #' @param info a [logical] to indicate info should be printed - the default is `TRUE` only in interactive mode #' @param include_unknown a [logical] to indicate whether 'unknown' microorganisms should be included too, i.e. microbial code `"UNKNOWN"`, which defaults to `FALSE`. For WHONET users, this means that all records with organism code `"con"` (*contamination*) will be excluded at default. Isolates with a microbial ID of `NA` will always be excluded as first isolate. #' @param include_untested_sir a [logical] to indicate whether also rows without antibiotic results are still eligible for becoming a first isolate. Use `include_untested_sir = FALSE` to always return `FALSE` for such rows. This checks the data set for columns of class `sir` and consequently requires transforming columns with antibiotic results using [as.sir()] first. #' @param ... arguments passed on to [first_isolate()] when using [filter_first_isolate()], otherwise arguments passed on to [key_antimicrobials()] (such as `universal`, `gram_negative`, `gram_positive`) #' @details #' To conduct epidemiological analyses on antimicrobial resistance data, only so-called first isolates should be included to prevent overestimation and underestimation of antimicrobial resistance. Different methods can be used to do so, see below. #' #' These functions are context-aware. This means that the `x` argument can be left blank if used inside a [data.frame] call, see *Examples*. #' #' The [first_isolate()] function is a wrapper around the [is_new_episode()] function, but more efficient for data sets containing microorganism codes or names. #' #' All isolates with a microbial ID of `NA` will be excluded as first isolate. #' #' ### Different methods #' #' According to Hindler *et al.* (2007, \doi{10.1086/511864}), there are different methods (algorithms) to select first isolates with increasing reliability: isolate-based, patient-based, episode-based and phenotype-based. All methods select on a combination of the taxonomic genus and species (not subspecies). #' #' All mentioned methods are covered in the [first_isolate()] function: #' #' #' | **Method** | **Function to apply** | #' |--------------------------------------------------|-------------------------------------------------------| #' | **Isolate-based** | `first_isolate(x, method = "isolate-based")` | #' | *(= all isolates)* | | #' | | | #' | | | #' | **Patient-based** | `first_isolate(x, method = "patient-based")` | #' | *(= first isolate per patient)* | | #' | | | #' | | | #' | **Episode-based** | `first_isolate(x, method = "episode-based")`, or: | #' | *(= first isolate per episode)* | | #' | - 7-Day interval from initial isolate | - `first_isolate(x, method = "e", episode_days = 7)` | #' | - 30-Day interval from initial isolate | - `first_isolate(x, method = "e", episode_days = 30)` | #' | | | #' | | | #' | **Phenotype-based** | `first_isolate(x, method = "phenotype-based")`, or: | #' | *(= first isolate per phenotype)* | | #' | - Major difference in any antimicrobial result | - `first_isolate(x, type = "points")` | #' | - Any difference in key antimicrobial results | - `first_isolate(x, type = "keyantimicrobials")` | #' #' ### Isolate-based #' #' This method does not require any selection, as all isolates should be included. It does, however, respect all arguments set in the [first_isolate()] function. For example, the default setting for `include_unknown` (`FALSE`) will omit selection of rows without a microbial ID. #' #' ### Patient-based #' #' To include every genus-species combination per patient once, set the `episode_days` to `Inf`. Although often inappropriate, this method makes sure that no duplicate isolates are selected from the same patient. In a large longitudinal data set, this could mean that isolates are *excluded* that were found years after the initial isolate. #' #' ### Episode-based #' #' To include every genus-species combination per patient episode once, set the `episode_days` to a sensible number of days. Depending on the type of analysis, this could be 14, 30, 60 or 365. Short episodes are common for analysing specific hospital or ward data, long episodes are common for analysing regional and national data. #' #' This is the most common method to correct for duplicate isolates. Patients are categorised into episodes based on their ID and dates (e.g., the date of specimen receipt or laboratory result). While this is a common method, it does not take into account antimicrobial test results. This means that e.g. a methicillin-resistant *Staphylococcus aureus* (MRSA) isolate cannot be differentiated from a wildtype *Staphylococcus aureus* isolate. #' #' ### Phenotype-based #' #' This is a more reliable method, since it also *weighs* the antibiogram (antimicrobial test results) yielding so-called 'first weighted isolates'. There are two different methods to weigh the antibiogram: #' #' 1. Using `type = "points"` and argument `points_threshold` (default) #' #' This method weighs *all* antimicrobial drugs available in the data set. Any difference from I to S or R (or vice versa) counts as `0.5` points, a difference from S to R (or vice versa) counts as `1` point. When the sum of points exceeds `points_threshold`, which defaults to `2`, an isolate will be selected as a first weighted isolate. #' #' All antimicrobials are internally selected using the [all_antimicrobials()] function. The output of this function does not need to be passed to the [first_isolate()] function. #' #' #' 2. Using `type = "keyantimicrobials"` and argument `ignore_I` #' #' This method only weighs specific antimicrobial drugs, called *key antimicrobials*. Any difference from S to R (or vice versa) in these key antimicrobials will select an isolate as a first weighted isolate. With `ignore_I = FALSE`, also differences from I to S or R (or vice versa) will lead to this. #' #' Key antimicrobials are internally selected using the [key_antimicrobials()] function, but can also be added manually as a variable to the data and set in the `col_keyantimicrobials` argument. Another option is to pass the output of the [key_antimicrobials()] function directly to the `col_keyantimicrobials` argument. #' #' #' The default method is phenotype-based (using `type = "points"`) and episode-based (using `episode_days = 365`). This makes sure that every genus-species combination is selected per patient once per year, while taking into account all antimicrobial test results. If no antimicrobial test results are available in the data set, only the episode-based method is applied at default. #' @rdname first_isolate #' @seealso [key_antimicrobials()] #' @export #' @return A [logical] vector #' @source Methodology of this function is strictly based on: #' #' - **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/>. #' #' - Hindler JF and Stelling J (2007). **Analysis and Presentation of Cumulative Antibiograms: A New Consensus Guideline from the Clinical and Laboratory Standards Institute.** Clinical Infectious Diseases, 44(6), 867-873. \doi{10.1086/511864} #' @examples #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates. #' #' example_isolates[first_isolate(info = TRUE), ] #' \donttest{ #' # get all first Gram-negatives #' example_isolates[which(first_isolate(info = FALSE) & mo_is_gram_negative()), ] #' #' if (require("dplyr")) { #' # filter on first isolates using dplyr: #' example_isolates %>% #' filter(first_isolate(info = TRUE)) #' } #' if (require("dplyr")) { #' # short-hand version: #' example_isolates %>% #' filter_first_isolate(info = FALSE) #' } #' if (require("dplyr")) { #' # flag the first isolates per group: #' example_isolates %>% #' group_by(ward) %>% #' mutate(first = first_isolate(info = TRUE)) %>% #' select(ward, date, patient, mo, first) #' } #' } first_isolate <- function(x = NULL, col_date = NULL, col_patient_id = NULL, col_mo = NULL, col_testcode = NULL, col_specimen = NULL, col_icu = NULL, col_keyantimicrobials = NULL, episode_days = 365, testcodes_exclude = NULL, icu_exclude = FALSE, specimen_group = NULL, type = "points", method = c("phenotype-based", "episode-based", "patient-based", "isolate-based"), ignore_I = TRUE, points_threshold = 2, info = interactive(), include_unknown = FALSE, include_untested_sir = TRUE, ...) { if (is_null_or_grouped_tbl(x)) { # when `x` is left blank, auto determine it (get_current_data() searches underlying data within call) # is also fix for using a grouped df as input (a dot as first argument) x <- tryCatch(get_current_data(arg_name = "x", call = -2), error = function(e) x) } meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0 meet_criteria(col_date, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(col_patient_id, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(col_testcode, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) if (isFALSE(col_specimen)) { col_specimen <- NULL } meet_criteria(col_specimen, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) if (is.logical(col_icu)) { meet_criteria(col_icu, allow_class = "logical", has_length = c(1, nrow(x)), allow_NA = TRUE, allow_NULL = TRUE) x$newvar_is_icu <- col_icu } else if (!is.null(col_icu)) { # add "logical" to the allowed classes here, since it may give an error in certain user input, and should then also say that logicals can be used too meet_criteria(col_icu, allow_class = c("character", "logical"), has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) x$newvar_is_icu <- x[, col_icu, drop = TRUE] } else { x$newvar_is_icu <- NA } # method method <- coerce_method(method) meet_criteria(method, allow_class = "character", has_length = 1, is_in = c("phenotype-based", "episode-based", "patient-based", "isolate-based")) # key antimicrobials if (length(col_keyantimicrobials) > 1) { meet_criteria(col_keyantimicrobials, allow_class = "character", has_length = nrow(x)) x$keyabcol <- col_keyantimicrobials col_keyantimicrobials <- "keyabcol" } else { if (isFALSE(col_keyantimicrobials)) { col_keyantimicrobials <- NULL # method cannot be phenotype-based anymore if (method == "phenotype-based") { method <- "episode-based" } } meet_criteria(col_keyantimicrobials, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) } meet_criteria(episode_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE) meet_criteria(testcodes_exclude, allow_class = "character", allow_NULL = TRUE) meet_criteria(icu_exclude, allow_class = "logical", has_length = 1) meet_criteria(specimen_group, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(type, allow_class = "character", has_length = 1, is_in = c("points", "keyantimicrobials")) meet_criteria(ignore_I, allow_class = "logical", has_length = 1) meet_criteria(points_threshold, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(info, allow_class = "logical", has_length = 1) meet_criteria(include_unknown, allow_class = "logical", has_length = 1) if ("include_untested_rsi" %in% names(list(...))) { deprecation_warning("include_untested_rsi", "include_untested_sir", is_function = FALSE) include_untested_sir <- list(...)$include_untested_rsi } meet_criteria(include_untested_sir, allow_class = "logical", has_length = 1) # remove data.table, grouping from tibbles, etc. x <- as.data.frame(x, stringsAsFactors = FALSE) any_col_contains_sir <- any(vapply( FUN.VALUE = logical(1), X = x, # check only first 10,000 rows FUN = function(x) any(as.character(x[1:10000]) %in% c("S", "I", "R"), na.rm = TRUE), USE.NAMES = FALSE )) if (method == "phenotype-based" && !any_col_contains_sir) { method <- "episode-based" } if (isTRUE(info) && message_not_thrown_before("first_isolate", "method")) { message_( paste0( "Determining first isolates ", ifelse(method %in% c("episode-based", "phenotype-based"), ifelse(is.infinite(episode_days), paste(font_bold("without"), " a specified episode length"), paste("using an episode length of", font_bold(paste(episode_days, "days"))) ), "" ) ), add_fn = font_red ) } # try to find columns based on type # -- mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = info) stop_if(is.null(col_mo), "`col_mo` must be set") } # methods ---- if (method == "isolate-based") { episode_days <- Inf col_keyantimicrobials <- NULL x$dummy_dates <- Sys.Date() col_date <- "dummy_dates" x$dummy_patients <- paste("dummy", seq_len(nrow(x))) # all 'patients' must be unique col_patient_id <- "dummy_patients" } else if (method == "patient-based") { episode_days <- Inf col_keyantimicrobials <- NULL } else if (method == "episode-based") { col_keyantimicrobials <- NULL } else if (method == "phenotype-based") { if (missing(type) && !is.null(col_keyantimicrobials)) { # type = "points" is default, but not set explicitly, while col_keyantimicrobials is type <- "keyantimicrobials" } if (type == "points") { x$keyantimicrobials <- all_antimicrobials(x, only_sir_columns = FALSE) col_keyantimicrobials <- "keyantimicrobials" } else if (type == "keyantimicrobials" && is.null(col_keyantimicrobials)) { col_keyantimicrobials <- search_type_in_df(x = x, type = "keyantimicrobials", info = info) if (is.null(col_keyantimicrobials)) { # still not found as a column, create it ourselves x$keyantimicrobials <- key_antimicrobials(x, only_sir_columns = FALSE, col_mo = col_mo, ...) col_keyantimicrobials <- "keyantimicrobials" } } } # -- date if (is.null(col_date)) { col_date <- search_type_in_df(x = x, type = "date", info = info) stop_if(is.null(col_date), "`col_date` must be set") } # -- patient id if (is.null(col_patient_id)) { if (all(c("First name", "Last name", "Sex") %in% colnames(x))) { # WHONET support x$patient_id <- paste(x$`First name`, x$`Last name`, x$Sex) col_patient_id <- "patient_id" message_("Using combined columns '", font_bold("First name"), "', '", font_bold("Last name"), "' and '", font_bold("Sex"), "' as input for `col_patient_id`") } else { col_patient_id <- search_type_in_df(x = x, type = "patient_id", info = info) } stop_if(is.null(col_patient_id), "`col_patient_id` must be set") } # -- specimen if (is.null(col_specimen) && !is.null(specimen_group)) { col_specimen <- search_type_in_df(x = x, type = "specimen", info = info) } # check if columns exist check_columns_existance <- function(column, tblname = x) { if (!is.null(column)) { stop_ifnot(column %in% colnames(tblname), "Column '", column, "' not found.", call = FALSE ) } } check_columns_existance(col_date) check_columns_existance(col_patient_id) check_columns_existance(col_mo) check_columns_existance(col_testcode) check_columns_existance(col_keyantimicrobials) # convert dates to Date dates <- as.Date(x[, col_date, drop = TRUE]) dates[is.na(dates)] <- as.Date("1970-01-01") x[, col_date] <- dates # create original row index x$newvar_row_index <- seq_len(nrow(x)) x$newvar_mo <- as.mo(x[, col_mo, drop = TRUE], keep_synonyms = TRUE, info = FALSE) x$newvar_genus_species <- paste(mo_genus(x$newvar_mo, keep_synonyms = TRUE, info = FALSE), mo_species(x$newvar_mo, keep_synonyms = TRUE, info = FALSE)) x$newvar_date <- x[, col_date, drop = TRUE] x$newvar_patient_id <- as.character(x[, col_patient_id, drop = TRUE]) if (is.null(col_testcode)) { testcodes_exclude <- NULL } # remove testcodes if (!is.null(testcodes_exclude) && isTRUE(info) && message_not_thrown_before("first_isolate", "excludingtestcodes")) { message_("Excluding test codes: ", vector_and(testcodes_exclude, quotes = TRUE), add_fn = font_red ) } if (is.null(col_specimen)) { specimen_group <- NULL } # filter on specimen group and keyantibiotics when they are filled in if (!is.null(specimen_group)) { check_columns_existance(col_specimen, x) if (isTRUE(info) && message_not_thrown_before("first_isolate", "excludingspecimen")) { message_("Excluding other than specimen group '", specimen_group, "'", add_fn = font_red ) } } if (!is.null(col_keyantimicrobials)) { x$newvar_key_ab <- as.character(x[, col_keyantimicrobials, drop = TRUE]) } if (is.null(testcodes_exclude)) { testcodes_exclude <- "" } # arrange data to the right sorting if (is.null(specimen_group)) { x <- x[order( x$newvar_patient_id, x$newvar_genus_species, x$newvar_date ), ] rownames(x) <- NULL row.start <- 1 row.end <- nrow(x) } else { # filtering on specimen and only analyse these rows to save time x <- x[order( pm_pull(x, col_specimen), x$newvar_patient_id, x$newvar_genus_species, x$newvar_date ), ] rownames(x) <- NULL suppressWarnings( row.start <- which(x %pm>% pm_pull(col_specimen) == specimen_group) %pm>% min(na.rm = TRUE) ) suppressWarnings( row.end <- which(x %pm>% pm_pull(col_specimen) == specimen_group) %pm>% max(na.rm = TRUE) ) } # speed up - return immediately if obvious if (abs(row.start) == Inf || abs(row.end) == Inf) { if (isTRUE(info)) { message_("=> Found ", font_bold("no isolates"), add_fn = font_black, as_note = FALSE ) } return(rep(FALSE, nrow(x))) } if (row.start == row.end) { if (isTRUE(info)) { message_("=> Found ", font_bold("1 first isolate"), ", as the data only contained 1 row", add_fn = font_black, as_note = FALSE ) } return(TRUE) } if (length(c(row.start:row.end)) == pm_n_distinct(x[c(row.start:row.end), col_mo, drop = TRUE])) { if (isTRUE(info)) { message_("=> Found ", font_bold(paste(length(c(row.start:row.end)), "first isolates")), ", as all isolates were different microbial species", add_fn = font_black, as_note = FALSE ) } return(rep(TRUE, length(c(row.start:row.end)))) } # did find some isolates - add new index numbers of rows x$newvar_row_index_sorted <- seq_len(nrow(x)) scope.size <- nrow(x[which(x$newvar_row_index_sorted %in% seq(row.start, row.end, 1) & !is.na(x$newvar_mo)), , drop = FALSE]) # Analysis of first isolate ---- if (!is.null(col_keyantimicrobials)) { if (isTRUE(info) && message_not_thrown_before("first_isolate", "type")) { if (type == "keyantimicrobials") { message_("Basing inclusion on key antimicrobials, ", ifelse(ignore_I == FALSE, "not ", ""), "ignoring I", add_fn = font_red ) } if (type == "points") { message_("Basing inclusion on all antimicrobial results, using a points threshold of ", points_threshold, add_fn = font_red ) } } } x$other_pat_or_mo <- !(x$newvar_patient_id == pm_lag(x$newvar_patient_id) & x$newvar_genus_species == pm_lag(x$newvar_genus_species)) x$newvar_episode_group <- paste(x$newvar_patient_id, x$newvar_genus_species) x$more_than_episode_ago <- unlist( lapply( split( x$newvar_date, x$newvar_episode_group ), is_new_episode, episode_days = episode_days, drop = FALSE ), use.names = FALSE ) if (!is.null(col_keyantimicrobials)) { # using phenotypes x$different_antibiogram <- !unlist( lapply( split( x$newvar_key_ab, x$newvar_episode_group ), duplicated_antibiogram, points_threshold = points_threshold, ignore_I = ignore_I, type = type ), use.names = FALSE ) } else { x$different_antibiogram <- FALSE } x$newvar_first_isolate <- x$newvar_row_index_sorted >= row.start & x$newvar_row_index_sorted <= row.end & x$newvar_genus_species != "" & (x$other_pat_or_mo | x$more_than_episode_ago | x$different_antibiogram) decimal.mark <- getOption("OutDec") big.mark <- ifelse(decimal.mark != ",", ",", " ") # first one as TRUE x[row.start, "newvar_first_isolate"] <- TRUE # no tests that should be included, or ICU if (!is.null(col_testcode)) { x[which(x[, col_testcode] %in% tolower(testcodes_exclude)), "newvar_first_isolate"] <- FALSE } if (any(!is.na(x$newvar_is_icu)) && any(x$newvar_is_icu == TRUE, na.rm = TRUE)) { if (icu_exclude == TRUE) { if (isTRUE(info)) { message_("Excluding ", format(sum(x$newvar_is_icu, na.rm = TRUE), decimal.mark = decimal.mark, big.mark = big.mark), " isolates from ICU.", add_fn = font_red) } x[which(x$newvar_is_icu), "newvar_first_isolate"] <- FALSE } else if (isTRUE(info)) { message_("Including isolates from ICU.") } } if (isTRUE(info)) { # print group name if used in dplyr::group_by() cur_group <- import_fn("cur_group", "dplyr", error_on_fail = FALSE) if (!is.null(cur_group)) { group_df <- tryCatch(cur_group(), error = function(e) data.frame()) if (NCOL(group_df) > 0) { # transform factors to characters group <- vapply(FUN.VALUE = character(1), group_df, function(x) { if (is.numeric(x)) { format(x) } else if (is.logical(x)) { as.character(x) } else { paste0('"', x, '"') } }) message_("\nGroup: ", paste0(names(group), " = ", group, collapse = ", "), "\n", as_note = FALSE, add_fn = font_red ) } } } # handle empty microorganisms if (any(x$newvar_mo == "UNKNOWN", na.rm = TRUE) && isTRUE(info)) { message_( ifelse(include_unknown == TRUE, "Including ", "Excluding "), format(sum(x$newvar_mo == "UNKNOWN", na.rm = TRUE), decimal.mark = decimal.mark, big.mark = big.mark ), " isolates with a microbial ID 'UNKNOWN' (in column '", font_bold(col_mo), "')", add_fn = font_red ) } x[which(x$newvar_mo == "UNKNOWN"), "newvar_first_isolate"] <- include_unknown # exclude all NAs if (anyNA(x$newvar_mo) && isTRUE(info)) { message_( "Excluding ", format(sum(is.na(x$newvar_mo), na.rm = TRUE), decimal.mark = decimal.mark, big.mark = big.mark ), " isolates with a microbial ID `NA` (in column '", font_bold(col_mo), "')", add_fn = font_red ) } x[which(is.na(x$newvar_mo)), "newvar_first_isolate"] <- FALSE # handle isolates without antibiogram if (include_untested_sir == FALSE && any(is.sir(x))) { sir_all_NA <- which(unname(vapply( FUN.VALUE = logical(1), as.data.frame(t(x[, is.sir(x), drop = FALSE])), function(sir_values) all(is.na(sir_values)) ))) x[sir_all_NA, "newvar_first_isolate"] <- FALSE } # arrange back according to original sorting again x <- x[order(x$newvar_row_index), , drop = FALSE] rownames(x) <- NULL if (isTRUE(info)) { n_found <- sum(x$newvar_first_isolate, na.rm = TRUE) p_found_total <- percentage(n_found / nrow(x[which(!is.na(x$newvar_mo)), , drop = FALSE]), digits = 1) p_found_scope <- percentage(n_found / scope.size, digits = 1) if (p_found_total %unlike% "[.]") { p_found_total <- gsub("%", ".0%", p_found_total, fixed = TRUE) } if (p_found_scope %unlike% "[.]") { p_found_scope <- gsub("%", ".0%", p_found_scope, fixed = TRUE) } # mark up number of found n_found <- format(n_found, big.mark = big.mark, decimal.mark = decimal.mark) message_( paste0( "=> Found ", font_bold(paste0( n_found, ifelse(method == "isolate-based", "", paste0(" '", method, "'")), " first isolates" )), " (", ifelse(p_found_total != p_found_scope, paste0(p_found_scope, " within scope and "), "" ), p_found_total, " of total where a microbial ID was available)" ), add_fn = font_black, as_note = FALSE ) } x$newvar_first_isolate } #' @rdname first_isolate #' @export filter_first_isolate <- function(x = NULL, col_date = NULL, col_patient_id = NULL, col_mo = NULL, episode_days = 365, method = c("phenotype-based", "episode-based", "patient-based", "isolate-based"), ...) { if (is_null_or_grouped_tbl(x)) { # when `x` is left blank, auto determine it (get_current_data() searches underlying data within call) # is also fix for using a grouped df as input (a dot as first argument) x <- tryCatch(get_current_data(arg_name = "x", call = -2), error = function(e) x) } meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0 meet_criteria(col_date, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(col_patient_id, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x)) meet_criteria(episode_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE) method <- coerce_method(method) meet_criteria(method, allow_class = "character", has_length = 1, is_in = c("phenotype-based", "episode-based", "patient-based", "isolate-based")) subset(x, first_isolate( x = x, col_date = col_date, col_patient_id = col_patient_id, col_mo = col_mo, episode_days = episode_days, method = method, ... )) } coerce_method <- function(method) { if (is.null(method)) { return(method) } method <- tolower(as.character(method[1L])) method[method %like% "^(p$|pheno)"] <- "phenotype-based" method[method %like% "^(e$|episode)"] <- "episode-based" method[method %like% "^pat"] <- "patient-based" method[method %like% "^(i$|iso)"] <- "isolate-based" method } duplicated_antibiogram <- function(antibiogram, points_threshold, ignore_I, type) { if (length(antibiogram) == 1) { # fast return, only 1 isolate return(FALSE) } out <- rep(NA, length(antibiogram)) out[1] <- FALSE out[2] <- antimicrobials_equal(antibiogram[1], antibiogram[2], ignore_I = ignore_I, points_threshold = points_threshold, type = type) if (length(antibiogram) == 2) { # fast return, no further check required return(out) } # sort after the second one (since we already determined AB equality of the first two) original_sort <- c(1, 2, rank(antibiogram[3:length(antibiogram)]) + 2) antibiogram.bak <- antibiogram antibiogram <- c(antibiogram[1:2], sort(antibiogram[3:length(antibiogram)])) # we can skip the duplicates - they are never unique antibiograms of course duplicates <- duplicated(antibiogram) out[3:length(out)][duplicates[3:length(out)] == TRUE] <- TRUE if (all(duplicates[3:length(out)] == TRUE, na.rm = TRUE)) { # fast return, no further check required return(c(out[1:2], rep(TRUE, length(out) - 2))) } for (na in antibiogram[is.na(out)]) { # check if this antibiogram has any change with other antibiograms out[which(antibiogram == na)] <- all( vapply(FUN.VALUE = logical(1), antibiogram[!is.na(out) & antibiogram != na], function(y) antimicrobials_equal(y = y, z = na, ignore_I = ignore_I, points_threshold = points_threshold, type = type))) } out <- out[original_sort] # rerun duplicated again duplicates <- duplicated(antibiogram.bak) out[duplicates == TRUE] <- TRUE out }
/scratch/gouwar.j/cran-all/cranData/AMR/R/first_isolate.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' *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 #' @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. #' #' The p-value is computed from the asymptotic chi-squared distribution of the test statistic. #' #' In the contingency table case simulation is done by random sampling from the set of all contingency tables with given marginals, and works only if the marginals are strictly positive. Note that this is not the usual sampling situation assumed for a chi-squared test (such as the *G*-test) but rather that for Fisher's exact test. #' #' In the goodness-of-fit case simulation is done by random sampling from the discrete distribution specified by `p`, each sample being of size `n = sum(x)`. This simulation is done in \R and may be slow. #' #' ### *G*-test Of Goodness-of-Fit (Likelihood Ratio Test) #' Use the *G*-test of goodness-of-fit when you have one nominal variable with two or more values (such as male and female, or red, pink and white flowers). You compare the observed counts of numbers of observations in each category with the expected counts, which you calculate using some kind of theoretical expectation (such as a 1:1 sex ratio or a 1:2:1 ratio in a genetic cross). #' #' If the expected number of observations in any category is too small, the *G*-test may give inaccurate results, and you should use an exact test instead ([fisher.test()]). #' #' The *G*-test of goodness-of-fit is an alternative to the chi-square test of goodness-of-fit ([chisq.test()]); each of these tests has some advantages and some disadvantages, and the results of the two tests are usually very similar. #' #' ### *G*-test of Independence #' Use the *G*-test of independence when you have two nominal variables, each with two or more possible values. You want to know whether the proportions for one variable are different among values of the other variable. #' #' It is also possible to do a *G*-test of independence with more than two nominal variables. For example, Jackson et al. (2013) also had data for children under 3, so you could do an analysis of old vs. young, thigh vs. arm, and reaction vs. no reaction, all analyzed together. #' #' Fisher's exact test ([fisher.test()]) is an **exact** test, where the *G*-test is still only an **approximation**. For any 2x2 table, Fisher's Exact test may be slower but will still run in seconds, even if the sum of your observations is multiple millions. #' #' The *G*-test of independence is an alternative to the chi-square test of independence ([chisq.test()]), and they will give approximately the same results. #' #' ### How the Test Works #' Unlike the exact test of goodness-of-fit ([fisher.test()]), the *G*-test does not directly calculate the probability of obtaining the observed results or something more extreme. Instead, like almost all statistical tests, the *G*-test has an intermediate step; it uses the data to calculate a test statistic that measures how far the observed data are from the null expectation. You then use a mathematical relationship, in this case the chi-square distribution, to estimate the probability of obtaining that value of the test statistic. #' #' The *G*-test uses the log of the ratio of two likelihoods as the test statistic, which is why it is also called a likelihood ratio test or log-likelihood ratio test. The formula to calculate a *G*-statistic is: #' #' \eqn{G = 2 * sum(x * log(x / E))} #' #' where `E` are the expected values. Since this is chi-square distributed, the p value can be calculated in \R with: #' ``` #' p <- stats::pchisq(G, df, lower.tail = FALSE) #' ``` #' where `df` are the degrees of freedom. #' #' 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. <http://www.biostathandbook.com/gtestgof.html>. #' @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 #' - The possibility to simulate p values with `simulate.p.value` was removed #' @export #' @importFrom stats pchisq complete.cases #' @examples #' # = EXAMPLE 1 = #' # Shivrain et al. (2006) crossed clearfield rice (which are resistant #' # to the herbicide imazethapyr) with red rice (which are susceptible to #' # imazethapyr). They then crossed the hybrid offspring and examined the #' # F2 generation, where they found 772 resistant plants, 1611 moderately #' # resistant plants, and 737 susceptible plants. If resistance is controlled #' # by a single gene with two co-dominant alleles, you would expect a 1:2:1 #' # ratio. #' #' x <- c(772, 1611, 737) #' g.test(x, p = c(1, 2, 1) / 4) #' #' # There is no significant difference from a 1:2:1 ratio. #' # Meaning: resistance controlled by a single gene with two co-dominant #' # alleles, is plausible. #' #' #' # = EXAMPLE 2 = #' # Red crossbills (Loxia curvirostra) have the tip of the upper bill either #' # right or left of the lower bill, which helps them extract seeds from pine #' # cones. Some have hypothesized that frequency-dependent selection would #' # keep the number of right and left-billed birds at a 1:1 ratio. Groth (1992) #' # observed 1752 right-billed and 1895 left-billed crossbills. #' #' x <- c(1752, 1895) #' g.test(x) #' #' # There is a significant difference from a 1:1 ratio. #' # Meaning: there are significantly more left-billed birds. g.test <- function(x, y = NULL, # correct = TRUE, p = rep(1 / length(x), length(x)), rescale.p = FALSE) { DNAME <- deparse(substitute(x)) if (is.data.frame(x)) { x <- as.matrix(x) } if (is.matrix(x)) { if (min(dim(x)) == 1L) { x <- as.vector(x) } } if (!is.matrix(x) && !is.null(y)) { if (length(x) != length(y)) { stop("'x' and 'y' must have the same length") } DNAME2 <- deparse(substitute(y)) xname <- if (length(DNAME) > 1L || nchar(DNAME, "w") > 30) { "" } else { DNAME } yname <- if (length(DNAME2) > 1L || nchar(DNAME2, "w") > 30) { "" } else { DNAME2 } OK <- complete.cases(x, y) x <- factor(x[OK]) y <- factor(y[OK]) if ((nlevels(x) < 2L) || (nlevels(y) < 2L)) { stop("'x' and 'y' must have at least 2 levels") } x <- table(x, y) names(dimnames(x)) <- c(xname, yname) DNAME <- paste( paste(DNAME, collapse = "\n"), "and", paste(DNAME2, collapse = "\n") ) } if (any(x < 0) || anyNA(x)) { stop("all entries of 'x' must be nonnegative and finite") } if ((n <- sum(x)) == 0) { stop("at least one entry of 'x' must be positive") } if (is.matrix(x)) { METHOD <- "G-test of independence" nr <- as.integer(nrow(x)) nc <- as.integer(ncol(x)) if (is.na(nr) || is.na(nc) || is.na(nr * nc)) { stop("invalid nrow(x) or ncol(x)", domain = NA) } # add fisher.test suggestion if (nr == 2 && nc == 2) { warning("`fisher.test()` is always more reliable for 2x2 tables and although much slower, often only takes seconds.") } sr <- rowSums(x) sc <- colSums(x) E <- outer(sr, sc, "*") / n v <- function(r, c, n) c * r * (n - r) * (n - c) / n^3 V <- outer(sr, sc, v, n) dimnames(E) <- dimnames(x) STATISTIC <- 2 * sum(x * log(x / E), na.rm = TRUE) # sum((abs(x - E) - YATES)^2/E) for chisq.test PARAMETER <- (nr - 1L) * (nc - 1L) PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE) } else { if (length(dim(x)) > 2L) { stop("invalid 'x'") } if (length(x) == 1L) { stop("'x' must at least have 2 elements") } if (length(x) != length(p)) { stop("'x' and 'p' must have the same number of elements") } if (any(p < 0)) { stop("probabilities must be non-negative.") } if (abs(sum(p) - 1) > sqrt(.Machine$double.eps)) { if (rescale.p) { p <- p / sum(p) } else { stop("probabilities must sum to 1.") } } METHOD <- "G-test of goodness-of-fit (likelihood ratio test)" E <- n * p V <- n * p * (1 - p) STATISTIC <- 2 * sum(x * log(x / E)) # sum((x - E)^2/E) for chisq.test names(E) <- names(x) PARAMETER <- length(x) - 1 PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE) } names(STATISTIC) <- "X-squared" names(PARAMETER) <- "df" if (any(E < 5) && is.finite(PARAMETER)) { warning("G-statistic approximation may be incorrect due to E < 5") } structure(list( statistic = STATISTIC, argument = PARAMETER, p.value = PVAL, method = METHOD, data.name = DNAME, observed = x, expected = E, residuals = (x - E) / sqrt(E), stdres = (x - E) / sqrt(V) ), class = "htest") }
/scratch/gouwar.j/cran-all/cranData/AMR/R/g.test.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Determine Clinical or Epidemic Episodes #' #' These functions determine which items in a vector can be considered (the start of) a new episode. This can be used to determine clinical episodes for any epidemiological analysis. The [get_episode()] function returns the index number of the episode per group, while the [is_new_episode()] function returns `TRUE` for every new [get_episode()] index. Both absolute and relative episode determination are supported. #' @param x vector of dates (class `Date` or `POSIXt`), will be sorted internally to determine episodes #' @param episode_days episode length in days to specify the time period after which a new episode begins, can also be less than a day or `Inf`, see *Details* #' @param case_free_days (inter-epidemic) interval length in days after which a new episode will start, can also be less than a day or `Inf`, see *Details* #' @param ... ignored, only in place to allow future extensions #' @details Episodes can be determined in two ways: absolute and relative. #' #' 1. Absolute #' #' This method uses `episode_days` to define an episode length in days, after which a new episode will start. A common use case in AMR data analysis is microbial epidemiology: episodes of *S. aureus* bacteraemia in ICU patients for example. The episode length could then be 30 days, so that new *S. aureus* isolates after an ICU episode of 30 days will be considered a different (or new) episode. #' #' Thus, this method counts **since the start of the previous episode**. #' #' 2. Relative #' #' This method uses `case_free_days` to quantify the duration of case-free days (the inter-epidemic interval), after which a new episode will start. A common use case is infectious disease epidemiology: episodes of norovirus outbreaks in a hospital for example. The case-free period could then be 14 days, so that new norovirus cases after that time will be considered a different (or new) episode. #' #' Thus, this methods counts **since the last case in the previous episode**. #' #' In a table: #' #' | Date | Using `episode_days = 7` | Using `case_free_days = 7` | #' |:----------:|:------------------------:|:--------------------------:| #' | 2023-01-01 | 1 | 1 | #' | 2023-01-02 | 1 | 1 | #' | 2023-01-05 | 1 | 1 | #' | 2023-01-08 | 2** | 1 | #' | 2023-02-21 | 3 | 2*** | #' | 2023-02-22 | 3 | 2 | #' | 2023-02-23 | 3 | 2 | #' | 2023-02-24 | 3 | 2 | #' | 2023-03-01 | 4 | 2 | #' #' ** This marks the start of a new episode, because 8 January 2023 is more than 7 days since the start of the previous episode (1 January 2023). \cr #' *** This marks the start of a new episode, because 21 January 2023 is more than 7 days since the last case in the previous episode (8 January 2023). #' #' Either `episode_days` or `case_free_days` must be provided in the function. #' #' ### Difference between `get_episode()` and `is_new_episode()` #' #' The [get_episode()] function returns the index number of the episode, so all cases/patients/isolates in the first episode will have the number 1, all cases/patients/isolates in the second episode will have the number 2, etc. #' #' The [is_new_episode()] function on the other hand, returns `TRUE` for every new [get_episode()] index. #' #' To specify, when setting `episode_days = 365` (using method 1 as explained above), this is how the two functions differ: #' #' | patient | date | `get_episode()` | `is_new_episode()` | #' |:---------:|:----------:|:---------------:|:------------------:| #' | A | 2019-01-01 | 1 | TRUE | #' | A | 2019-03-01 | 1 | FALSE | #' | A | 2021-01-01 | 2 | TRUE | #' | B | 2008-01-01 | 1 | TRUE | #' | B | 2008-01-01 | 1 | FALSE | #' | C | 2020-01-01 | 1 | TRUE | #' #' ### Other #' #' The [first_isolate()] function is a wrapper around the [is_new_episode()] function, but is more efficient for data sets containing microorganism codes or names and allows for different isolate selection methods. #' #' The `dplyr` package is not required for these functions to work, but these episode functions do support [variable grouping][dplyr::group_by()] and work conveniently inside `dplyr` verbs such as [`filter()`][dplyr::filter()], [`mutate()`][dplyr::mutate()] and [`summarise()`][dplyr::summarise()]. #' @return #' * [get_episode()]: an [integer] vector #' * [is_new_episode()]: a [logical] vector #' @seealso [first_isolate()] #' @rdname get_episode #' @export #' @examples #' # difference between absolute and relative determination of episodes: #' x <- data.frame(dates = as.Date(c( #' "2021-01-01", #' "2021-01-02", #' "2021-01-05", #' "2021-01-08", #' "2021-02-21", #' "2021-02-22", #' "2021-02-23", #' "2021-02-24", #' "2021-03-01", #' "2021-03-01" #' ))) #' x$absolute <- get_episode(x$dates, episode_days = 7) #' x$relative <- get_episode(x$dates, case_free_days = 7) #' x #' #' #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates #' df <- example_isolates[sample(seq_len(2000), size = 100), ] #' #' get_episode(df$date, episode_days = 60) # indices #' is_new_episode(df$date, episode_days = 60) # TRUE/FALSE #' #' # filter on results from the third 60-day episode only, using base R #' df[which(get_episode(df$date, 60) == 3), ] #' #' # the functions also work for less than a day, e.g. to include one per hour: #' get_episode( #' c( #' Sys.time(), #' Sys.time() + 60 * 60 #' ), #' episode_days = 1 / 24 #' ) #' #' \donttest{ #' if (require("dplyr")) { #' # is_new_episode() can also be used in dplyr verbs to determine patient #' # episodes based on any (combination of) grouping variables: #' df %>% #' mutate(condition = sample( #' x = c("A", "B", "C"), #' size = 100, #' replace = TRUE #' )) %>% #' group_by(patient, condition) %>% #' mutate(new_episode = is_new_episode(date, 365)) %>% #' select(patient, date, condition, new_episode) %>% #' arrange(patient, condition, date) #' } #' #' if (require("dplyr")) { #' df %>% #' group_by(ward, patient) %>% #' transmute(date, #' patient, #' new_index = get_episode(date, 60), #' new_logical = is_new_episode(date, 60) #' ) %>% #' arrange(patient, ward, date) #' } #' #' if (require("dplyr")) { #' df %>% #' group_by(ward) %>% #' summarise( #' n_patients = n_distinct(patient), #' n_episodes_365 = sum(is_new_episode(date, episode_days = 365)), #' n_episodes_60 = sum(is_new_episode(date, episode_days = 60)), #' n_episodes_30 = sum(is_new_episode(date, episode_days = 30)) #' ) #' } #' #' # grouping on patients and microorganisms leads to the same #' # results as first_isolate() when using 'episode-based': #' if (require("dplyr")) { #' x <- df %>% #' filter_first_isolate( #' include_unknown = TRUE, #' method = "episode-based" #' ) #' #' y <- df %>% #' group_by(patient, mo) %>% #' filter(is_new_episode(date, 365)) %>% #' ungroup() #' #' identical(x, y) #' } #' #' # but is_new_episode() has a lot more flexibility than first_isolate(), #' # since you can now group on anything that seems relevant: #' if (require("dplyr")) { #' df %>% #' group_by(patient, mo, ward) %>% #' mutate(flag_episode = is_new_episode(date, 365)) %>% #' select(group_vars(.), flag_episode) #' } #' } get_episode <- function(x, episode_days = NULL, case_free_days = NULL, ...) { meet_criteria(x, allow_class = c("Date", "POSIXt"), allow_NA = TRUE) meet_criteria(episode_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE, allow_NULL = TRUE) meet_criteria(case_free_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE, allow_NULL = TRUE) as.integer(exec_episode(x, episode_days, case_free_days, ...)) } #' @rdname get_episode #' @export is_new_episode <- function(x, episode_days = NULL, case_free_days = NULL, ...) { meet_criteria(x, allow_class = c("Date", "POSIXt"), allow_NA = TRUE) meet_criteria(episode_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE, allow_NULL = TRUE) meet_criteria(case_free_days, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = FALSE, allow_NULL = TRUE) !duplicated(exec_episode(x, episode_days, case_free_days, ...)) } exec_episode <- function(x, episode_days, case_free_days, ...) { stop_ifnot(is.null(episode_days) || is.null(case_free_days), "either argument `episode_days` or argument `case_free_days` must be set.", call = -2 ) # running as.double() on a POSIXct object will return its number of seconds since 1970-01-01 x <- as.double(as.POSIXct(x)) # as.POSIXct() required for Date classes # since x is now in seconds, get seconds from episode_days as well episode_seconds <- episode_days * 60 * 60 * 24 case_free_seconds <- case_free_days * 60 * 60 * 24 if (length(x) == 1) { # this will also match 1 NA, which is fine return(1) } else if (length(x) == 2 && all(!is.na(x))) { if ((length(episode_seconds) > 0 && (max(x) - min(x)) >= episode_seconds) || (length(case_free_seconds) > 0 && (max(x) - min(x)) >= case_free_seconds)) { if (x[1] <= x[2]) { return(c(1, 2)) } else { return(c(2, 1)) } } else { return(c(1, 1)) } } run_episodes <- function(x, episode_sec, case_free_sec) { NAs <- which(is.na(x)) x[NAs] <- 0 indices <- integer(length = length(x)) start <- x[1] ind <- 1 indices[ind] <- 1 for (i in 2:length(x)) { if ((length(episode_sec) > 0 && (x[i] - start) >= episode_sec) || (length(case_free_sec) > 0 && (x[i] - x[i - 1]) >= case_free_sec)) { ind <- ind + 1 start <- x[i] } indices[i] <- ind } indices[NAs] <- NA indices } ord <- order(x) out <- run_episodes(x[ord], episode_seconds, case_free_seconds)[order(ord)] out[is.na(x) & ord != 1] <- NA # every NA expect for the first must remain NA out }
/scratch/gouwar.j/cran-all/cranData/AMR/R/get_episode.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' PCA Biplot with `ggplot2` #' #' 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 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) #' @param groups an optional vector of groups for the labels, with the same length as `labels`. If set, the points and labels will be coloured according to these groups. When using the [pca()] function as input for `x`, this will be determined automatically based on the attribute `non_numeric_cols`, see [pca()]. #' @param ellipse a [logical] to indicate whether a normal data ellipse should be drawn for each group (set with `groups`) #' @param ellipse_prob statistical size of the ellipse in normal probability #' @param ellipse_size the size of the ellipse line #' @param ellipse_alpha the alpha (transparency) of the ellipse line #' @param points_size the size of the points #' @param points_alpha the alpha (transparency) of the points #' @param arrows a [logical] to indicate whether arrows should be drawn #' @param arrows_textsize the size of the text for variable names #' @param arrows_colour the colour of the arrow and their text #' @param arrows_size the size (thickness) of the arrow lines #' @param arrows_textsize the size of the text at the end of the arrows #' @param arrows_textangled a [logical] whether the text at the end of the arrows should be angled #' @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 #' @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: #' 1. Rewritten code to remove the dependency on packages `plyr`, `scales` and `grid` #' 2. Parametrised more options, like arrow and ellipse settings #' 3. Hardened all input possibilities by defining the exact type of user input for every argument #' 4. Added total amount of explained variance as a caption in the plot #' 5. Cleaned all syntax based on the `lintr` package, fixed grammatical errors and added integrity checks #' 6. Updated documentation #' @details The colours for labels and points can be changed by adding another scale layer for colour, such as `scale_colour_viridis_d()` and `scale_colour_brewer()`. #' @rdname ggplot_pca #' @export #' @examples #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates. #' #' \donttest{ #' if (require("dplyr")) { #' # calculate the resistance per group first #' resistance_data <- example_isolates %>% #' group_by( #' order = mo_order(mo), # group on anything, like order #' genus = mo_genus(mo) #' ) %>% # and genus as we do here; #' filter(n() >= 30) %>% # filter on only 30 results per group #' summarise_if(is.sir, resistance) # then get resistance of all drugs #' #' # now conduct PCA for certain antimicrobial drugs #' pca_result <- resistance_data %>% #' pca(AMC, CXM, CTX, CAZ, GEN, TOB, TMP, SXT) #' #' summary(pca_result) #' #' # old base R plotting method: #' biplot(pca_result) #' #' # new ggplot2 plotting method using this package: #' if (require("ggplot2")) { #' ggplot_pca(pca_result) #' #' # still extendible with any ggplot2 function #' ggplot_pca(pca_result) + #' scale_colour_viridis_d() + #' labs(title = "Title here") #' } #' } #' } ggplot_pca <- function(x, choices = 1:2, scale = 1, pc.biplot = TRUE, labels = NULL, labels_textsize = 3, labels_text_placement = 1.5, groups = NULL, ellipse = TRUE, ellipse_prob = 0.68, ellipse_size = 0.5, ellipse_alpha = 0.5, points_size = 2, points_alpha = 0.25, arrows = TRUE, arrows_colour = "darkblue", arrows_size = 0.5, arrows_textsize = 3, arrows_textangled = TRUE, arrows_alpha = 0.75, base_textsize = 10, ...) { stop_ifnot_installed("ggplot2") meet_criteria(x, allow_class = c("prcomp", "princomp", "PCA", "lda")) meet_criteria(choices, allow_class = c("numeric", "integer"), has_length = 2, is_positive = TRUE, is_finite = TRUE) meet_criteria(scale, allow_class = c("numeric", "integer", "logical"), has_length = 1) meet_criteria(pc.biplot, allow_class = "logical", has_length = 1) meet_criteria(labels, allow_class = "character", allow_NULL = TRUE) meet_criteria(labels_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(labels_text_placement, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(groups, allow_class = "character", allow_NULL = TRUE) meet_criteria(ellipse, allow_class = "logical", has_length = 1) meet_criteria(ellipse_prob, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(ellipse_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(ellipse_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(points_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(points_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(arrows, allow_class = "logical", has_length = 1) meet_criteria(arrows_colour, allow_class = "character", has_length = 1) meet_criteria(arrows_size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(arrows_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(arrows_textangled, allow_class = "logical", has_length = 1) meet_criteria(arrows_alpha, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(base_textsize, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) calculations <- pca_calculations( pca_model = x, groups = groups, groups_missing = missing(groups), labels = labels, labels_missing = missing(labels), choices = choices, scale = scale, pc.biplot = pc.biplot, ellipse_prob = ellipse_prob, labels_text_placement = labels_text_placement ) choices <- calculations$choices df.u <- calculations$df.u df.v <- calculations$df.v ell <- calculations$ell groups <- calculations$groups group_name <- calculations$group_name labels <- calculations$labels # Append the proportion of explained variance to the axis labels if ((1 - as.integer(scale)) == 0) { u.axis.labs <- paste0("Standardised PC", choices) } else { u.axis.labs <- paste0("PC", choices) } u.axis.labs <- paste0( u.axis.labs, paste0( "\n(explained var: ", percentage(x$sdev[choices]^2 / sum(x$sdev^2)), ")" ) ) # Score Labels if (!is.null(labels)) { df.u$labels <- labels } # Grouping variable if (!is.null(groups)) { df.u$groups <- groups } # Base plot g <- ggplot2::ggplot( data = df.u, ggplot2::aes(x = xvar, y = yvar) ) + ggplot2::xlab(u.axis.labs[1]) + ggplot2::ylab(u.axis.labs[2]) + ggplot2::expand_limits( x = c(-1.15, 1.15), y = c(-1.15, 1.15) ) # Draw either labels or points if (!is.null(df.u$labels)) { if (!is.null(df.u$groups)) { g <- g + ggplot2::geom_point(ggplot2::aes(colour = groups), alpha = points_alpha, size = points_size ) + ggplot2::geom_text(ggplot2::aes(label = labels, colour = groups), nudge_y = -0.05, size = labels_textsize ) + ggplot2::labs(colour = group_name) } else { g <- g + ggplot2::geom_point( alpha = points_alpha, size = points_size ) + ggplot2::geom_text(ggplot2::aes(label = labels), nudge_y = -0.05, size = labels_textsize ) } } else { if (!is.null(df.u$groups)) { g <- g + ggplot2::geom_point(ggplot2::aes(colour = groups), alpha = points_alpha, size = points_size ) + ggplot2::labs(colour = group_name) } else { g <- g + ggplot2::geom_point( alpha = points_alpha, size = points_size ) } } # Overlay a concentration ellipse if there are groups if (!is.null(df.u$groups) && !is.null(ell) && isTRUE(ellipse)) { g <- g + ggplot2::geom_path( data = ell, ggplot2::aes(colour = groups, group = groups), size = ellipse_size, alpha = points_alpha ) } # Label the variable axes if (arrows == TRUE) { g <- g + ggplot2::geom_segment( data = df.v, ggplot2::aes(x = 0, y = 0, xend = xvar, yend = yvar), arrow = ggplot2::arrow( length = ggplot2::unit(0.5, "picas"), angle = 20, ends = "last", type = "open" ), colour = arrows_colour, size = arrows_size, alpha = arrows_alpha ) if (arrows_textangled == TRUE) { g <- g + ggplot2::geom_text( data = df.v, ggplot2::aes(label = varname, x = xvar, y = yvar, angle = angle, hjust = hjust), colour = arrows_colour, size = arrows_textsize, alpha = arrows_alpha ) } else { g <- g + ggplot2::geom_text( data = df.v, ggplot2::aes(label = varname, x = xvar, y = yvar, hjust = hjust), colour = arrows_colour, size = arrows_textsize, alpha = arrows_alpha ) } } # Add caption label about total explained variance g <- g + ggplot2::labs(caption = paste0( "Total explained variance: ", percentage(sum(x$sdev[choices]^2 / sum(x$sdev^2))) )) # mark-up nicely g <- g + ggplot2::theme_minimal(base_size = base_textsize) + ggplot2::theme( panel.grid.major = ggplot2::element_line(colour = "grey85"), panel.grid.minor = ggplot2::element_blank(), # centre title and subtitle plot.title = ggplot2::element_text(hjust = 0.5), plot.subtitle = ggplot2::element_text(hjust = 0.5) ) g } #' @importFrom stats qchisq var pca_calculations <- function(pca_model, groups = NULL, groups_missing = TRUE, labels = NULL, labels_missing = TRUE, choices = 1:2, scale = 1, pc.biplot = TRUE, ellipse_prob = 0.68, labels_text_placement = 1.5) { non_numeric_cols <- attributes(pca_model)$non_numeric_cols if (groups_missing) { groups <- tryCatch(non_numeric_cols[[1]], error = function(e) NULL ) group_name <- tryCatch(colnames(non_numeric_cols[1]), error = function(e) NULL ) } if (labels_missing) { labels <- tryCatch(non_numeric_cols[[2]], error = function(e) NULL ) } if (!is.null(groups) && is.null(labels)) { # turn them around labels <- groups groups <- NULL group_name <- NULL } # Recover the SVD if (inherits(pca_model, "prcomp")) { nobs.factor <- sqrt(nrow(pca_model$x) - 1) d <- pca_model$sdev u <- sweep(pca_model$x, 2, 1 / (d * nobs.factor), FUN = "*") v <- pca_model$rotation } else if (inherits(pca_model, "princomp")) { nobs.factor <- sqrt(pca_model$n.obs) d <- pca_model$sdev u <- sweep(pca_model$scores, 2, 1 / (d * nobs.factor), FUN = "*") v <- pca_model$loadings } else if (inherits(pca_model, "PCA")) { nobs.factor <- sqrt(nrow(pca_model$call$X)) d <- unlist(sqrt(pca_model$eig)[1]) u <- sweep(pca_model$ind$coord, 2, 1 / (d * nobs.factor), FUN = "*") v <- sweep(pca_model$var$coord, 2, sqrt(pca_model$eig[seq_len(ncol(pca_model$var$coord)), 1]), FUN = "/") } else if (inherits(pca_model, "lda")) { nobs.factor <- sqrt(pca_model$N) d <- pca_model$svd u <- predict(pca_model)$x / nobs.factor v <- pca_model$scaling } else { stop("Expected an object of class prcomp, princomp, PCA, or lda") } # Scores choices <- pmin(choices, ncol(u)) obs.scale <- 1 - as.integer(scale) df.u <- as.data.frame(sweep(u[, choices], 2, d[choices]^obs.scale, FUN = "*"), stringsAsFactors = FALSE ) # Directions v <- sweep(v, 2, d^as.integer(scale), FUN = "*") df.v <- as.data.frame(v[, choices], stringsAsFactors = FALSE ) names(df.u) <- c("xvar", "yvar") names(df.v) <- names(df.u) if (isTRUE(pc.biplot)) { df.u <- df.u * nobs.factor } # Scale the radius of the correlation circle so that it corresponds to # a data ellipse for the standardized PC scores circle_prob <- 0.69 r <- sqrt(qchisq(circle_prob, df = 2)) * prod(colMeans(df.u^2))^(0.25) # Scale directions v.scale <- rowSums(v^2) df.v <- r * df.v / sqrt(max(v.scale)) # Grouping variable if (!is.null(groups)) { df.u$groups <- groups } df.v$varname <- rownames(v) # Variables for text label placement df.v$angle <- with(df.v, (180 / pi) * atan(yvar / xvar)) df.v$hjust <- with(df.v, (1 - labels_text_placement * sign(xvar)) / 2) if (!is.null(df.u$groups)) { theta <- c(seq(-pi, pi, length = 50), seq(pi, -pi, length = 50)) circle <- cbind(cos(theta), sin(theta)) df.groups <- lapply(unique(df.u$groups), function(g, df = df.u) { x <- df[which(df$groups == g), , drop = FALSE] if (nrow(x) <= 2) { return(data.frame( X1 = numeric(0), X2 = numeric(0), groups = character(0), stringsAsFactors = FALSE )) } sigma <- var(cbind(x$xvar, x$yvar)) mu <- c(mean(x$xvar), mean(x$yvar)) ed <- sqrt(qchisq(ellipse_prob, df = 2)) data.frame( sweep(circle %*% chol(sigma) * ed, MARGIN = 2, STATS = mu, FUN = "+" ), groups = x$groups[1], stringsAsFactors = FALSE ) }) ell <- do.call(rbind, df.groups) if (NROW(ell) == 0) { ell <- NULL } else { names(ell)[1:2] <- c("xvar", "yvar") } } else { ell <- NULL } list( choices = choices, df.u = df.u, df.v = df.v, ell = ell, groups = groups, group_name = group_name, labels = labels ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/ggplot_pca.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' AMR Plots with `ggplot2` #' #' Use these functions to create bar plots for AMR data analysis. All functions rely on [ggplot2][ggplot2::ggplot()] functions. #' @param data a [data.frame] with column(s) of class [`sir`] (see [as.sir()]) #' @param position position adjustment of bars, either `"fill"`, `"stack"` or `"dodge"` #' @param x variable to show on x axis, either `"antibiotic"` (default) or `"interpretation"` or a grouping variable #' @param fill variable to categorise using the plots legend, either `"antibiotic"` (default) or `"interpretation"` or a grouping variable #' @param breaks a [numeric] vector of positions #' @param limits a [numeric] vector of length two providing limits of the scale, use `NA` to refer to the existing minimum or maximum #' @param facet variable to split plots by, either `"interpretation"` (default) or `"antibiotic"` or a grouping variable #' @inheritParams proportion #' @param nrow (when using `facet`) number of rows #' @param colours a named vactor with colour to be used for filling. The default colours are colour-blind friendly. #' @param aesthetics aesthetics to apply the colours to - the default is "fill" but can also be (a combination of) "alpha", "colour", "fill", "linetype", "shape" or "size" #' @param datalabels show datalabels using [labels_sir_count()] #' @param datalabels.size size of the datalabels #' @param datalabels.colour colour of the datalabels #' @param title text to show as title of the plot #' @param subtitle text to show as subtitle of the plot #' @param caption text to show as caption of the plot #' @param x.title text to show as x axis description #' @param y.title text to show as y axis description #' @param ... other arguments passed on to [geom_sir()] or, in case of [scale_sir_colours()], named values to set colours. The default colours are colour-blind friendly, while maintaining the convention that e.g. 'susceptible' should be green and 'resistant' should be red. See *Examples*. #' @details At default, the names of antibiotics will be shown on the plots using [ab_name()]. This can be set with the `translate_ab` argument. See [count_df()]. #' #' ### The Functions #' [geom_sir()] will take any variable from the data that has an [`sir`] class (created with [as.sir()]) using [sir_df()] and will plot bars with the percentage S, I, and R. The default behaviour is to have the bars stacked and to have the different antibiotics on the x axis. #' #' [facet_sir()] creates 2d plots (at default based on S/I/R) using [ggplot2::facet_wrap()]. #' #' [scale_y_percent()] transforms the y axis to a 0 to 100% range using [ggplot2::scale_y_continuous()]. #' #' [scale_sir_colours()] sets colours to the bars (green for S, yellow for I, and red for R). with multilingual support. The default colours are colour-blind friendly, while maintaining the convention that e.g. 'susceptible' should be green and 'resistant' should be red. #' #' [theme_sir()] is a [ggplot2 theme][[ggplot2::theme()] with minimal distraction. #' #' [labels_sir_count()] print datalabels on the bars with percentage and amount of isolates using [ggplot2::geom_text()]. #' #' [ggplot_sir()] is a wrapper around all above functions that uses data as first input. This makes it possible to use this function after a pipe (`%>%`). See *Examples*. #' @rdname ggplot_sir #' @export #' @examples #' \donttest{ #' if (require("ggplot2") && require("dplyr")) { #' # get antimicrobial results for drugs against a UTI: #' ggplot(example_isolates %>% select(AMX, NIT, FOS, TMP, CIP)) + #' geom_sir() #' } #' if (require("ggplot2") && require("dplyr")) { #' # prettify the plot using some additional functions: #' df <- example_isolates %>% select(AMX, NIT, FOS, TMP, CIP) #' ggplot(df) + #' geom_sir() + #' scale_y_percent() + #' scale_sir_colours() + #' labels_sir_count() + #' theme_sir() #' } #' if (require("ggplot2") && require("dplyr")) { #' # or better yet, simplify this using the wrapper function - a single command: #' example_isolates %>% #' select(AMX, NIT, FOS, TMP, CIP) %>% #' ggplot_sir() #' } #' if (require("ggplot2") && require("dplyr")) { #' # get only proportions and no counts: #' example_isolates %>% #' select(AMX, NIT, FOS, TMP, CIP) %>% #' ggplot_sir(datalabels = FALSE) #' } #' if (require("ggplot2") && require("dplyr")) { #' # add other ggplot2 arguments as you like: #' example_isolates %>% #' select(AMX, NIT, FOS, TMP, CIP) %>% #' ggplot_sir( #' width = 0.5, #' colour = "black", #' size = 1, #' linetype = 2, #' alpha = 0.25 #' ) #' } #' if (require("ggplot2") && require("dplyr")) { #' # you can alter the colours with colour names: #' example_isolates %>% #' select(AMX) %>% #' ggplot_sir(colours = c(SI = "yellow")) #' } #' if (require("ggplot2") && require("dplyr")) { #' # but you can also use the built-in colour-blind friendly colours for #' # your plots, where "S" is green, "I" is yellow and "R" is red: #' data.frame( #' x = c("Value1", "Value2", "Value3"), #' y = c(1, 2, 3), #' z = c("Value4", "Value5", "Value6") #' ) %>% #' ggplot() + #' geom_col(aes(x = x, y = y, fill = z)) + #' scale_sir_colours(Value4 = "S", Value5 = "I", Value6 = "R") #' } #' if (require("ggplot2") && require("dplyr")) { #' # resistance of ciprofloxacine per age group #' example_isolates %>% #' mutate(first_isolate = first_isolate()) %>% #' filter( #' first_isolate == TRUE, #' mo == as.mo("Escherichia coli") #' ) %>% #' # age_groups() is also a function in this AMR package: #' group_by(age_group = age_groups(age)) %>% #' select(age_group, CIP) %>% #' ggplot_sir(x = "age_group") #' } #' if (require("ggplot2") && require("dplyr")) { #' # a shorter version which also adjusts data label colours: #' example_isolates %>% #' select(AMX, NIT, FOS, TMP, CIP) %>% #' ggplot_sir(colours = FALSE) #' } #' if (require("ggplot2") && require("dplyr")) { #' # it also supports groups (don't forget to use the group var on `x` or `facet`): #' example_isolates %>% #' filter(mo_is_gram_negative(), ward != "Outpatient") %>% #' # select only UTI-specific drugs #' select(ward, AMX, NIT, FOS, TMP, CIP) %>% #' group_by(ward) %>% #' ggplot_sir( #' x = "ward", #' facet = "antibiotic", #' nrow = 1, #' title = "AMR of Anti-UTI Drugs Per Ward", #' x.title = "Ward", #' datalabels = FALSE #' ) #' } #' } ggplot_sir <- function(data, position = NULL, x = "antibiotic", fill = "interpretation", # params = list(), facet = NULL, breaks = seq(0, 1, 0.1), limits = NULL, translate_ab = "name", combine_SI = TRUE, minimum = 30, language = get_AMR_locale(), nrow = NULL, colours = c( S = "#3CAEA3", SI = "#3CAEA3", I = "#F6D55C", IR = "#ED553B", R = "#ED553B" ), datalabels = TRUE, datalabels.size = 2.5, datalabels.colour = "grey15", title = NULL, subtitle = NULL, caption = NULL, x.title = "Antimicrobial", y.title = "Proportion", ...) { stop_ifnot_installed("ggplot2") meet_criteria(data, allow_class = "data.frame", contains_column_class = c("sir", "rsi")) meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE) meet_criteria(x, allow_class = "character", has_length = 1) meet_criteria(fill, allow_class = "character", has_length = 1) meet_criteria(facet, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(breaks, allow_class = c("numeric", "integer")) meet_criteria(limits, allow_class = c("numeric", "integer"), has_length = 2, allow_NULL = TRUE, allow_NA = TRUE) meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) language <- validate_language(language) meet_criteria(nrow, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive = TRUE, is_finite = TRUE) meet_criteria(colours, allow_class = c("character", "logical")) meet_criteria(datalabels, allow_class = "logical", has_length = 1) meet_criteria(datalabels.size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(datalabels.colour, allow_class = "character", has_length = 1) meet_criteria(title, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(subtitle, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(caption, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(x.title, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(y.title, allow_class = "character", has_length = 1, allow_NULL = TRUE) # we work with aes_string later on x_deparse <- deparse(substitute(x)) if (x_deparse != "x") { x <- x_deparse } if (x %like% '".*"') { x <- substr(x, 2, nchar(x) - 1) } facet_deparse <- deparse(substitute(facet)) if (facet_deparse != "facet") { facet <- facet_deparse } if (facet %like% '".*"') { facet <- substr(facet, 2, nchar(facet) - 1) } if (facet %in% c("NULL", "")) { facet <- NULL } if (is.null(position)) { position <- "fill" } p <- ggplot2::ggplot(data = data) + geom_sir( position = position, x = x, fill = fill, translate_ab = translate_ab, minimum = minimum, language = language, combine_SI = combine_SI, ... ) + theme_sir() if (fill == "interpretation") { p <- p + scale_sir_colours(colours = colours) } if (identical(position, "fill")) { # proportions, so use y scale with percentage p <- p + scale_y_percent(breaks = breaks, limits = limits) } if (datalabels == TRUE) { p <- p + labels_sir_count( position = position, x = x, translate_ab = translate_ab, minimum = minimum, language = language, combine_SI = combine_SI, datalabels.size = datalabels.size, datalabels.colour = datalabels.colour ) } if (!is.null(facet)) { p <- p + facet_sir(facet = facet, nrow = nrow) } p <- p + ggplot2::labs( title = title, subtitle = subtitle, caption = caption, x = x.title, y = y.title ) p } #' @rdname ggplot_sir #' @export geom_sir <- function(position = NULL, x = c("antibiotic", "interpretation"), fill = "interpretation", translate_ab = "name", minimum = 30, language = get_AMR_locale(), combine_SI = TRUE, ...) { x <- x[1] stop_ifnot_installed("ggplot2") stop_if(is.data.frame(position), "`position` is invalid. Did you accidentally use '%>%' instead of '+'?") meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE) meet_criteria(x, allow_class = "character", has_length = 1) meet_criteria(fill, allow_class = "character", has_length = 1) meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) language <- validate_language(language) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) y <- "value" if (missing(position) || is.null(position)) { position <- "fill" } if (identical(position, "fill")) { position <- ggplot2::position_fill(vjust = 0.5, reverse = TRUE) } # we work with aes_string later on x_deparse <- deparse(substitute(x)) if (x_deparse != "x") { x <- x_deparse } if (x %like% '".*"') { x <- substr(x, 2, nchar(x) - 1) } if (tolower(x) %in% tolower(c("ab", "abx", "antibiotics"))) { x <- "antibiotic" } else if (tolower(x) %in% tolower(c("SIR", "sir", "interpretations", "result"))) { x <- "interpretation" } ggplot2::geom_col( data = function(x) { sir_df( data = x, translate_ab = translate_ab, language = language, minimum = minimum, combine_SI = combine_SI ) }, mapping = ggplot2::aes_string(x = x, y = y, fill = fill), position = position, ... ) } #' @rdname ggplot_sir #' @export facet_sir <- function(facet = c("interpretation", "antibiotic"), nrow = NULL) { facet <- facet[1] stop_ifnot_installed("ggplot2") meet_criteria(facet, allow_class = "character", has_length = 1) meet_criteria(nrow, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive = TRUE, is_finite = TRUE) # we work with aes_string later on facet_deparse <- deparse(substitute(facet)) if (facet_deparse != "facet") { facet <- facet_deparse } if (facet %like% '".*"') { facet <- substr(facet, 2, nchar(facet) - 1) } if (tolower(facet) %in% tolower(c("SIR", "sir", "interpretations", "result"))) { facet <- "interpretation" } else if (tolower(facet) %in% tolower(c("ab", "abx", "antibiotics"))) { facet <- "antibiotic" } ggplot2::facet_wrap(facets = facet, scales = "free_x", nrow = nrow) } #' @rdname ggplot_sir #' @export scale_y_percent <- function(breaks = seq(0, 1, 0.1), limits = NULL) { stop_ifnot_installed("ggplot2") meet_criteria(breaks, allow_class = c("numeric", "integer")) meet_criteria(limits, allow_class = c("numeric", "integer"), has_length = 2, allow_NULL = TRUE, allow_NA = TRUE) if (all(breaks[breaks != 0] > 1)) { breaks <- breaks / 100 } ggplot2::scale_y_continuous( breaks = breaks, labels = percentage(breaks), limits = limits ) } #' @rdname ggplot_sir #' @export scale_sir_colours <- function(..., aesthetics = "fill") { stop_ifnot_installed("ggplot2") meet_criteria(aesthetics, allow_class = "character", is_in = c("alpha", "colour", "color", "fill", "linetype", "shape", "size")) # behaviour until AMR pkg v1.5.0 and also when coming from ggplot_sir() if ("colours" %in% names(list(...))) { original_cols <- c( S = "#3CAEA3", SI = "#3CAEA3", I = "#F6D55C", IR = "#ED553B", R = "#ED553B" ) colours <- replace(original_cols, names(list(...)$colours), list(...)$colours) # limits = force is needed in ggplot2 3.3.4 and 3.3.5, see here; # https://github.com/tidyverse/ggplot2/issues/4511#issuecomment-866185530 return(ggplot2::scale_fill_manual(values = colours, limits = force)) } if (identical(unlist(list(...)), FALSE)) { return(invisible()) } 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", "Susceptible, incr. exp.", unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Intermediate"), "replacement", drop = TRUE ]), 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"), "replacement", drop = TRUE ]) ) susceptible <- rep("#3CAEA3", length(names_susceptible)) names(susceptible) <- names_susceptible incr_exposure <- rep("#F6D55C", length(names_incr_exposure)) names(incr_exposure) <- names_incr_exposure resistant <- rep("#ED553B", length(names_resistant)) names(resistant) <- names_resistant original_cols <- c(susceptible, incr_exposure, resistant) dots <- c(...) # replace S, I, R as colours: scale_sir_colours(mydatavalue = "S") dots[dots == "S"] <- "#3CAEA3" dots[dots == "I"] <- "#F6D55C" dots[dots == "R"] <- "#ED553B" cols <- replace(original_cols, names(dots), dots) # limits = force is needed in ggplot2 3.3.4 and 3.3.5, see here; # https://github.com/tidyverse/ggplot2/issues/4511#issuecomment-866185530 ggplot2::scale_discrete_manual(aesthetics = aesthetics, values = cols, limits = force) } #' @rdname ggplot_sir #' @export theme_sir <- function() { stop_ifnot_installed("ggplot2") ggplot2::theme_minimal(base_size = 10) + ggplot2::theme( panel.grid.major.x = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), panel.grid.major.y = ggplot2::element_line(colour = "grey75"), # center title and subtitle plot.title = ggplot2::element_text(hjust = 0.5), plot.subtitle = ggplot2::element_text(hjust = 0.5) ) } #' @rdname ggplot_sir #' @export labels_sir_count <- function(position = NULL, x = "antibiotic", translate_ab = "name", minimum = 30, language = get_AMR_locale(), combine_SI = TRUE, datalabels.size = 3, datalabels.colour = "grey15") { stop_ifnot_installed("ggplot2") meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE) meet_criteria(x, allow_class = "character", has_length = 1) meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) language <- validate_language(language) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(datalabels.size, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(datalabels.colour, allow_class = "character", has_length = 1) if (is.null(position)) { position <- "fill" } if (identical(position, "fill")) { position <- ggplot2::position_fill(vjust = 0.5, reverse = TRUE) } x_name <- x ggplot2::geom_text( mapping = ggplot2::aes_string( label = "lbl", x = x, y = "value" ), position = position, inherit.aes = FALSE, size = datalabels.size, colour = datalabels.colour, lineheight = 0.75, data = function(x) { transformed <- sir_df( data = x, translate_ab = translate_ab, combine_SI = combine_SI, minimum = minimum, language = language ) transformed$gr <- transformed[, x_name, drop = TRUE] transformed %pm>% pm_group_by(gr) %pm>% pm_mutate(lbl = paste0("n=", isolates)) %pm>% pm_ungroup() %pm>% pm_select(-gr) } ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/ggplot_sir.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Guess Antibiotic Column #' #' This tries to find a column name in a data set based on information from the [antibiotics] data set. Also supports WHONET abbreviations. #' @param x a [data.frame] #' @param search_string a text to search `x` for, will be checked with [as.ab()] if this value is not a column in `x` #' @param verbose a [logical] to indicate whether additional info should be printed #' @param only_sir_columns a [logical] to indicate whether only antibiotic columns must be detected that were transformed to class `sir` (see [as.sir()]) on beforehand (default is `FALSE`) #' @details You can look for an antibiotic (trade) name or abbreviation and it will search `x` and the [antibiotics] data set for any column containing a name or code of that antibiotic. #' @return A column name of `x`, or `NULL` when no result is found. #' @export #' @examples #' df <- data.frame( #' amox = "S", #' tetr = "R" #' ) #' #' guess_ab_col(df, "amoxicillin") #' guess_ab_col(df, "J01AA07") # ATC code of tetracycline #' #' guess_ab_col(df, "J01AA07", verbose = TRUE) #' # NOTE: Using column 'tetr' as input for J01AA07 (tetracycline). #' #' # WHONET codes #' df <- data.frame( #' AMP_ND10 = "R", #' AMC_ED20 = "S" #' ) #' guess_ab_col(df, "ampicillin") #' guess_ab_col(df, "J01CR02") #' guess_ab_col(df, as.ab("augmentin")) guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE, only_sir_columns = FALSE) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(search_string, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(verbose, allow_class = "logical", has_length = 1) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if (is.null(x) && is.null(search_string)) { return(as.name("guess_ab_col")) } else { meet_criteria(search_string, allow_class = "character", has_length = 1, allow_NULL = FALSE) } all_found <- get_column_abx(x, info = verbose, only_sir_columns = only_sir_columns, verbose = verbose, fn = "guess_ab_col" ) search_string.ab <- suppressWarnings(as.ab(search_string)) ab_result <- unname(all_found[names(all_found) == search_string.ab]) if (length(ab_result) == 0) { if (isTRUE(verbose)) { message_("No column found as input for ", search_string, " (", ab_name(search_string, language = NULL, tolower = TRUE), ").", add_fn = font_black, as_note = FALSE ) } return(NULL) } else { if (isTRUE(verbose)) { message_( "Using column '", font_bold(ab_result), "' as input for ", search_string, " (", ab_name(search_string, language = NULL, tolower = TRUE), ")." ) } return(ab_result) } } get_column_abx <- function(x, ..., soft_dependencies = NULL, hard_dependencies = NULL, verbose = FALSE, info = TRUE, only_sir_columns = FALSE, sort = TRUE, reuse_previous_result = TRUE, fn = NULL) { # check if retrieved before, then get it from package environment if (isTRUE(reuse_previous_result) && identical( unique_call_id( entire_session = FALSE, match_fn = fn ), AMR_env$get_column_abx.call )) { # so within the same call, within the same environment, we got here again. # but we could've come from another function within the same call, so now only check the columns that changed # first remove the columns that are not existing anymore previous <- AMR_env$get_column_abx.out current <- previous[previous %in% colnames(x)] # then compare columns in current call with columns in original call new_cols <- colnames(x)[!colnames(x) %in% AMR_env$get_column_abx.checked_cols] if (length(new_cols) > 0) { # these columns did not exist in the last call, so add them new_cols_sir <- get_column_abx(x[, new_cols, drop = FALSE], reuse_previous_result = FALSE, info = FALSE, sort = FALSE) current <- c(current, new_cols_sir) # order according to columns in current call current <- current[match(colnames(x)[colnames(x) %in% current], current)] } # update pkg environment to improve speed on next run AMR_env$get_column_abx.out <- current AMR_env$get_column_abx.checked_cols <- colnames(x) # and return right values return(AMR_env$get_column_abx.out) } meet_criteria(x, allow_class = "data.frame") meet_criteria(soft_dependencies, allow_class = "character", allow_NULL = TRUE) meet_criteria(hard_dependencies, allow_class = "character", allow_NULL = TRUE) meet_criteria(verbose, allow_class = "logical", has_length = 1) meet_criteria(info, allow_class = "logical", has_length = 1) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) meet_criteria(sort, allow_class = "logical", has_length = 1) if (isTRUE(info)) { message_("Auto-guessing columns suitable for analysis", appendLF = FALSE, as_note = FALSE) } x <- as.data.frame(x, stringsAsFactors = FALSE) x.bak <- x if (only_sir_columns == TRUE) { x <- x[, which(is.sir(x)), drop = FALSE] } if (NROW(x) > 10000) { # only test maximum of 10,000 values per column if (isTRUE(info)) { message_(" (using only ", font_bold("the first 10,000 rows"), ")...", appendLF = FALSE, as_note = FALSE ) } x <- x[1:10000, , drop = FALSE] } else if (isTRUE(info)) { message_("...", appendLF = FALSE, as_note = FALSE) } # only check columns that are a valid AB code, ATC code, name, abbreviation or synonym, # or already have the 'sir' class (as.sir) # and that they have no more than 50% invalid values vectr_antibiotics <- unlist(AMR_env$AB_lookup$generalised_all) vectr_antibiotics <- vectr_antibiotics[!is.na(vectr_antibiotics) & nchar(vectr_antibiotics) >= 3] x_columns <- vapply( FUN.VALUE = character(1), colnames(x), function(col, df = x) { if (generalise_antibiotic_name(col) %in% vectr_antibiotics || is.sir(x[, col, drop = TRUE]) || is_sir_eligible(x[, col, drop = TRUE], threshold = 0.5) ) { return(col) } else { return(NA_character_) } }, USE.NAMES = FALSE ) x_columns <- x_columns[!is.na(x_columns)] x <- x[, x_columns, drop = FALSE] # without drop = FALSE, x will become a vector when x_columns is length 1 df_trans <- data.frame( colnames = colnames(x), abcode = suppressWarnings(as.ab(colnames(x), info = FALSE)), stringsAsFactors = FALSE ) df_trans <- df_trans[!is.na(df_trans$abcode), , drop = FALSE] out <- as.character(df_trans$colnames) names(out) <- df_trans$abcode # add from self-defined dots (...): # such as get_column_abx(example_isolates %>% rename(thisone = AMX), amox = "thisone") all_okay <- TRUE dots <- list(...) # remove data.frames, since this is also used running `eucast_rules(eucast_rules_df = df)` dots <- dots[!vapply(FUN.VALUE = logical(1), dots, is.data.frame)] if (length(dots) > 0) { newnames <- suppressWarnings(as.ab(names(dots), info = FALSE)) if (anyNA(newnames)) { if (isTRUE(info)) { message_(" WARNING", add_fn = list(font_yellow, font_bold), as_note = FALSE) } warning_("Invalid antibiotic reference(s): ", vector_and(names(dots)[is.na(newnames)], quotes = FALSE), call = FALSE, immediate = TRUE ) all_okay <- FALSE } unexisting_cols <- which(!vapply(FUN.VALUE = logical(1), dots, function(col) all(col %in% x_columns))) if (length(unexisting_cols) > 0) { if (isTRUE(info)) { message_(" ERROR", add_fn = list(font_red, font_bold), as_note = FALSE) } stop_("Column(s) not found: ", vector_and(unlist(dots[[unexisting_cols]]), quotes = FALSE), call = FALSE ) all_okay <- FALSE } # turn all NULLs to NAs dots <- unlist(lapply(dots, function(dot) if (is.null(dot)) NA else dot)) names(dots) <- newnames dots <- dots[!is.na(names(dots))] # merge, but overwrite automatically determined ones by 'dots' out <- c(out[!out %in% dots & !names(out) %in% names(dots)], dots) # delete NAs, this will make e.g. eucast_rules(... TMP = NULL) work to prevent TMP from being used out <- out[!is.na(out)] } if (length(out) == 0) { if (isTRUE(info) && all_okay == TRUE) { message_("No columns found.") } AMR_env$get_column_abx.call <- unique_call_id(entire_session = FALSE, match_fn = fn) AMR_env$get_column_abx.checked_cols <- colnames(x.bak) AMR_env$get_column_abx.out <- out return(out) } # sort on name if (sort == TRUE) { out <- out[order(names(out), out)] } # only keep the first hits, no duplicates duplicates <- c(out[duplicated(names(out))], out[duplicated(unname(out))]) if (length(duplicates) > 0) { all_okay <- FALSE } if (isTRUE(info)) { if (all_okay == TRUE) { message_(" OK.", add_fn = list(font_green, font_bold), as_note = FALSE) } else { message_(" WARNING.", add_fn = list(font_yellow, font_bold), as_note = FALSE) } for (i in seq_len(length(out))) { if (isTRUE(verbose) && !names(out[i]) %in% names(duplicates)) { message_( "Using column '", font_bold(out[i]), "' as input for ", names(out)[i], " (", ab_name(names(out)[i], tolower = TRUE, language = NULL), ")." ) } if (names(out[i]) %in% names(duplicates)) { already_set_as <- out[unname(out) == unname(out[i])][1L] warning_( paste0( "Column '", font_bold(out[i]), "' will not be used for ", names(out)[i], " (", ab_name(names(out)[i], tolower = TRUE, language = NULL), ")", ", as it is already set for ", names(already_set_as), " (", ab_name(names(already_set_as), tolower = TRUE, language = NULL), ")" ), add_fn = font_red, immediate = verbose ) } } } out <- out[!duplicated(names(out))] out <- out[!duplicated(unname(out))] if (sort == TRUE) { out <- out[order(names(out), out)] } if (!is.null(hard_dependencies)) { hard_dependencies <- unique(hard_dependencies) if (!all(hard_dependencies %in% names(out))) { # missing a hard dependency will return NA and consequently the data will not be analysed missing <- hard_dependencies[!hard_dependencies %in% names(out)] generate_warning_abs_missing(missing, any = FALSE) return(NA) } } if (!is.null(soft_dependencies)) { soft_dependencies <- unique(soft_dependencies) if (isTRUE(info) && !all(soft_dependencies %in% names(out))) { # missing a soft dependency may lower the reliability missing <- soft_dependencies[!soft_dependencies %in% names(out)] missing_msg <- vector_and( paste0( ab_name(missing, tolower = TRUE, language = NULL), " (", font_bold(missing, collapse = NULL), ")" ), quotes = FALSE ) message_( "Reliability would be improved if these antimicrobial results would be available too: ", missing_msg ) } } AMR_env$get_column_abx.call <- unique_call_id(entire_session = FALSE, match_fn = fn) AMR_env$get_column_abx.checked_cols <- colnames(x.bak) AMR_env$get_column_abx.out <- out out } get_ab_from_namespace <- function(x, cols_ab) { # cols_ab comes from get_column_abx() x <- trimws2(unique(toupper(unlist(strsplit(x, ",", fixed = TRUE))))) x_new <- character() for (val in x) { if (paste0("AB_", val) %in% ls(envir = asNamespace("AMR"))) { # antibiotic group names, as defined in data-raw/_pre_commit_hook.R, such as `AB_CARBAPENEMS` val <- eval(parse(text = paste0("AB_", val)), envir = asNamespace("AMR")) } else if (val %in% AMR_env$AB_lookup$ab) { # separate drugs, such as `AMX` val <- as.ab(val) } else { stop_("unknown antimicrobial drug (group): ", val, call = FALSE) } x_new <- c(x_new, val) } x_new <- unique(x_new) out <- cols_ab[match(x_new, names(cols_ab))] out[!is.na(out)] } generate_warning_abs_missing <- function(missing, any = FALSE) { missing <- paste0(missing, " (", ab_name(missing, tolower = TRUE, language = NULL), ")") if (any == TRUE) { any_txt <- c(" any of", "is") } else { any_txt <- c("", "are") } warning_( paste0( "Introducing NAs since", any_txt[1], " these antimicrobials ", any_txt[2], " required: ", vector_and(missing, quotes = FALSE) ), immediate = TRUE ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/guess_ab_col.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Italicise Taxonomic Families, Genera, Species, Subspecies #' #' According to the binomial nomenclature, the lowest four taxonomic levels (family, genus, species, subspecies) should be printed in italics. This function finds taxonomic names within strings and makes them italic. #' @param string a [character] (vector) #' @param type type of conversion of the taxonomic names, either "markdown" or "ansi", see *Details* #' @details #' This function finds the taxonomic names and makes them italic based on the [microorganisms] data set. #' #' The taxonomic names can be italicised using markdown (the default) by adding `*` before and after the taxonomic names, or using ANSI colours by adding `\033[3m` before and `\033[23m` after the taxonomic names. If multiple ANSI colours are not available, no conversion will occur. #' #' This function also supports abbreviation of the genus if it is followed by a species, such as "E. coli" and "K. pneumoniae ozaenae". #' @export #' @examples #' italicise_taxonomy("An overview of Staphylococcus aureus isolates") #' italicise_taxonomy("An overview of S. aureus isolates") #' #' cat(italicise_taxonomy("An overview of S. aureus isolates", type = "ansi")) italicise_taxonomy <- function(string, type = c("markdown", "ansi")) { if (missing(type)) { type <- "markdown" } meet_criteria(string, allow_class = "character") meet_criteria(type, allow_class = "character", has_length = 1, is_in = c("markdown", "ansi")) add_MO_lookup_to_AMR_env() if (type == "markdown") { before <- "*" after <- "*" } else if (type == "ansi") { if (!has_colour() && !identical(Sys.getenv("IN_PKGDOWN"), "true")) { return(string) } before <- "\033[3m" after <- "\033[23m" } vapply( FUN.VALUE = character(1), string, function(s) { s_split <- unlist(strsplit(s, " ", fixed = TRUE)) search_strings <- gsub("[^a-zA-Z-]", "", s_split) ind_species <- search_strings != "" & search_strings %in% AMR_env$MO_lookup[ which(AMR_env$MO_lookup$rank %in% c( "family", "genus", "species", "subspecies", "infraspecies", "subsp." )), "species", drop = TRUE ] ind_fullname <- search_strings != "" & search_strings %in% c( AMR_env$MO_lookup[ which(AMR_env$MO_lookup$rank %in% c( "family", "genus", "species", "subspecies", "infraspecies", "subsp." )), "fullname", drop = TRUE ], AMR_env$MO_lookup[ which(AMR_env$MO_lookup$rank %in% c( "family", "genus", "species", "subspecies", "infraspecies", "subsp." )), "subspecies", drop = TRUE ] ) # also support E. coli, add "E." to indices has_previous_genera_abbr <- s_split[which(ind_species) - 1] %like_case% "^[A-Z][.]?$" ind_species <- c(which(ind_species), which(ind_species)[has_previous_genera_abbr] - 1) ind <- c(ind_species, which(ind_fullname)) s_split[ind] <- paste0(before, s_split[ind], after) s_paste <- paste(s_split, collapse = " ") # clean up a bit s_paste <- gsub(paste0(after, " ", before), " ", s_paste, fixed = TRUE) s_paste }, USE.NAMES = FALSE ) } #' @rdname italicise_taxonomy #' @export italicize_taxonomy <- function(string, type = c("markdown", "ansi")) { if (missing(type)) { type <- "markdown" } italicise_taxonomy(string = string, type = type) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/italicise_taxonomy.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Join [microorganisms] to a Data Set #' #' Join the data set [microorganisms] easily to an existing data set or to a [character] vector. #' @rdname join #' @name join #' @aliases join inner_join #' @param x existing data set to join, or [character] vector. In case of a [character] vector, the resulting [data.frame] will contain a column 'x' with these values. #' @param by a variable to join by - if left empty will search for a column with class [`mo`] (created with [as.mo()]) or will be `"mo"` if that column name exists in `x`, could otherwise be a column name of `x` with values that exist in `microorganisms$mo` (such as `by = "bacteria_id"`), or another column in [microorganisms] (but then it should be named, like `by = c("bacteria_id" = "fullname")`) #' @param suffix if there are non-joined duplicate variables in `x` and `y`, these suffixes will be added to the output to disambiguate them. Should be a [character] vector of length 2. #' @param ... ignored, only in place to allow future extensions #' @details **Note:** As opposed to the `join()` functions of `dplyr`, [character] vectors are supported and at default existing columns will get a suffix `"2"` and the newly joined columns will not get a suffix. #' #' If the `dplyr` package is installed, their join functions will be used. Otherwise, the much slower [merge()] and [interaction()] functions from base \R will be used. #' @return a [data.frame] #' @export #' @examples #' left_join_microorganisms(as.mo("K. pneumoniae")) #' left_join_microorganisms("B_KLBSL_PNMN") #' #' df <- data.frame( #' date = seq( #' from = as.Date("2018-01-01"), #' to = as.Date("2018-01-07"), #' by = 1 #' ), #' bacteria = as.mo(c( #' "S. aureus", "MRSA", "MSSA", "STAAUR", #' "E. coli", "E. coli", "E. coli" #' )), #' stringsAsFactors = FALSE #' ) #' colnames(df) #' #' df_joined <- left_join_microorganisms(df, "bacteria") #' colnames(df_joined) #' #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' left_join_microorganisms() %>% #' colnames() #' } #' } inner_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) meet_criteria(suffix, allow_class = "character", has_length = 2) join_microorganisms(type = "inner_join", x = x, by = by, suffix = suffix, ...) } #' @rdname join #' @export left_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) meet_criteria(suffix, allow_class = "character", has_length = 2) join_microorganisms(type = "left_join", x = x, by = by, suffix = suffix, ...) } #' @rdname join #' @export right_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) meet_criteria(suffix, allow_class = "character", has_length = 2) join_microorganisms(type = "right_join", x = x, by = by, suffix = suffix, ...) } #' @rdname join #' @export full_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) meet_criteria(suffix, allow_class = "character", has_length = 2) join_microorganisms(type = "full_join", x = x, by = by, suffix = suffix, ...) } #' @rdname join #' @export semi_join_microorganisms <- function(x, by = NULL, ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) join_microorganisms(type = "semi_join", x = x, by = by, ...) } #' @rdname join #' @export anti_join_microorganisms <- function(x, by = NULL, ...) { meet_criteria(x, allow_class = c("data.frame", "character")) meet_criteria(by, allow_class = "character", allow_NULL = TRUE) join_microorganisms(type = "anti_join", x = x, by = by, ...) } join_microorganisms <- function(type, x, by, suffix, ...) { add_MO_lookup_to_AMR_env() if (!is.data.frame(x)) { if (pkg_is_available("tibble")) { x <- import_fn("tibble", "tibble")(mo = x) } else { x <- data.frame(mo = x, stringsAsFactors = FALSE) } by <- "mo" } x.bak <- x if (is.null(by)) { by <- search_type_in_df(x, "mo", info = FALSE) if (is.null(by) && NCOL(x) == 1) { by <- colnames(x)[1L] } else { stop_if(is.null(by), "no column with microorganism names or codes found, set this column with `by`", call = -2) } message_('Joining, by = "', by, '"', add_fn = font_black, as_note = FALSE) # message same as dplyr::join functions } if (!all(x[, by, drop = TRUE] %in% AMR_env$MO_lookup$mo, na.rm = TRUE)) { x$join.mo <- as.mo(x[, by, drop = TRUE]) by <- c("join.mo" = "mo") } else { x[, by] <- as.mo(x[, by, drop = TRUE]) } if (is.null(names(by))) { # will always be joined to microorganisms$mo, so add name to that by <- stats::setNames("mo", by) } # use dplyr if available - it's much faster than poorman alternatives dplyr_join <- import_fn(name = type, pkg = "dplyr", error_on_fail = FALSE) if (!is.null(dplyr_join)) { join_fn <- dplyr_join } else { # otherwise use poorman, see R/aa_helper_pm_functions.R join_fn <- get(paste0("pm_", type), envir = asNamespace("AMR")) } MO_df <- AMR_env$MO_lookup[, colnames(AMR::microorganisms), drop = FALSE] if (type %like% "full|left|right|inner") { joined <- join_fn(x = x, y = MO_df, by = by, suffix = suffix, ...) } else { joined <- join_fn(x = x, y = MO_df, by = by, ...) } if ("join.mo" %in% colnames(joined)) { if ("mo" %in% colnames(joined)) { ind_mo <- which(colnames(joined) %in% c("mo", "join.mo")) colnames(joined)[ind_mo[1L]] <- paste0("mo", suffix[1L]) colnames(joined)[ind_mo[2L]] <- paste0("mo", suffix[2L]) } else { colnames(joined)[colnames(joined) == "join.mo"] <- "mo" } } if (type %like% "full|left|right|inner" && NROW(joined) > NROW(x)) { warning_("in `", type, "_microorganisms()`: the newly joined data set contains ", nrow(joined) - nrow(x), " rows more than the number of rows of `x`.") } as_original_data_class(joined, class(x.bak)) # will remove tibble groups }
/scratch/gouwar.j/cran-all/cranData/AMR/R/join_microorganisms.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' (Key) Antimicrobials for First Weighted Isolates #' #' These functions can be used to determine first weighted isolates by considering the phenotype for isolate selection (see [first_isolate()]). Using a phenotype-based method to determine first isolates is more reliable than methods that disregard phenotypes. #' @param x a [data.frame] with antibiotics columns, like `AMX` or `amox`. Can be left blank to determine automatically #' @param y,z [character] vectors to compare #' @inheritParams first_isolate #' @param universal names of **broad-spectrum** antimicrobial drugs, case-insensitive. Set to `NULL` to ignore. See *Details* for the default antimicrobial drugs #' @param gram_negative names of antibiotic drugs for **Gram-positives**, case-insensitive. Set to `NULL` to ignore. See *Details* for the default antibiotic drugs #' @param gram_positive names of antibiotic drugs for **Gram-negatives**, case-insensitive. Set to `NULL` to ignore. See *Details* for the default antibiotic drugs #' @param antifungal names of antifungal drugs for **fungi**, case-insensitive. Set to `NULL` to ignore. See *Details* for the default antifungal drugs #' @param only_sir_columns a [logical] to indicate whether only columns must be included that were transformed to class `sir` (see [as.sir()]) on beforehand (default is `FALSE`) #' @param ... ignored, only in place to allow future extensions #' @details #' The [key_antimicrobials()] and [all_antimicrobials()] functions are context-aware. This means that the `x` argument can be left blank if used inside a [data.frame] call, see *Examples*. #' #' The function [key_antimicrobials()] returns a [character] vector with 12 antimicrobial results for every isolate. The function [all_antimicrobials()] returns a [character] vector with all antimicrobial drug results for every isolate. These vectors can then be compared using [antimicrobials_equal()], to check if two isolates have generally the same antibiogram. Missing and invalid values are replaced with a dot (`"."`) by [key_antimicrobials()] and ignored by [antimicrobials_equal()]. #' #' Please see the [first_isolate()] function how these important functions enable the 'phenotype-based' method for determination of first isolates. #' #' The default antimicrobial drugs used for **all rows** (set in `universal`) are: #' #' - Ampicillin #' - Amoxicillin/clavulanic acid #' - Cefuroxime #' - Ciprofloxacin #' - Piperacillin/tazobactam #' - Trimethoprim/sulfamethoxazole #' #' The default antimicrobial drugs used for **Gram-negative bacteria** (set in `gram_negative`) are: #' #' - Cefotaxime #' - Ceftazidime #' - Colistin #' - Gentamicin #' - Meropenem #' - Tobramycin #' #' The default antimicrobial drugs used for **Gram-positive bacteria** (set in `gram_positive`) are: #' #' - Erythromycin #' - Oxacillin #' - Rifampin #' - Teicoplanin #' - Tetracycline #' - Vancomycin #' #' #' The default antimicrobial drugs used for **fungi** (set in `antifungal`) are: #' #' - Anidulafungin #' - Caspofungin #' - Fluconazole #' - Miconazole #' - Nystatin #' - Voriconazole #' @rdname key_antimicrobials #' @export #' @seealso [first_isolate()] #' @examples #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates. #' #' # output of the `key_antimicrobials()` function could be like this: #' strainA <- "SSSRR.S.R..S" #' strainB <- "SSSIRSSSRSSS" #' #' # those strings can be compared with: #' antimicrobials_equal(strainA, strainB, type = "keyantimicrobials") #' # TRUE, because I is ignored (as well as missing values) #' #' antimicrobials_equal(strainA, strainB, type = "keyantimicrobials", ignore_I = FALSE) #' # FALSE, because I is not ignored and so the 4th [character] differs #' #' \donttest{ #' if (require("dplyr")) { #' # set key antibiotics to a new variable #' my_patients <- example_isolates %>% #' mutate(keyab = key_antimicrobials(antifungal = NULL)) %>% # no need to define `x` #' mutate( #' # now calculate first isolates #' first_regular = first_isolate(col_keyantimicrobials = FALSE), #' # and first WEIGHTED isolates #' first_weighted = first_isolate(col_keyantimicrobials = "keyab") #' ) #' #' # Check the difference in this data set, 'weighted' results in more isolates: #' sum(my_patients$first_regular, na.rm = TRUE) #' sum(my_patients$first_weighted, na.rm = TRUE) #' } #' } key_antimicrobials <- function(x = NULL, col_mo = NULL, universal = c( "ampicillin", "amoxicillin/clavulanic acid", "cefuroxime", "piperacillin/tazobactam", "ciprofloxacin", "trimethoprim/sulfamethoxazole" ), gram_negative = c( "gentamicin", "tobramycin", "colistin", "cefotaxime", "ceftazidime", "meropenem" ), gram_positive = c( "vancomycin", "teicoplanin", "tetracycline", "erythromycin", "oxacillin", "rifampin" ), antifungal = c( "anidulafungin", "caspofungin", "fluconazole", "miconazole", "nystatin", "voriconazole" ), only_sir_columns = FALSE, ...) { if (is_null_or_grouped_tbl(x)) { # when `x` is left blank, auto determine it (get_current_data() searches underlying data within call) # is also fix for using a grouped df as input (a dot as first argument) x <- tryCatch(get_current_data(arg_name = "x", call = -2), error = function(e) x) } meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0 meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE, is_in = colnames(x)) meet_criteria(universal, allow_class = "character", allow_NULL = TRUE) meet_criteria(gram_negative, allow_class = "character", allow_NULL = TRUE) meet_criteria(gram_positive, allow_class = "character", allow_NULL = TRUE) meet_criteria(antifungal, allow_class = "character", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } # force regular data.frame, not a tibble or data.table x <- as.data.frame(x, stringsAsFactors = FALSE) cols <- get_column_abx(x, info = FALSE, only_sir_columns = only_sir_columns, fn = "key_antimicrobials") # try to find columns based on type # -- mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = FALSE) } if (is.null(col_mo)) { warning_("in `key_antimicrobials()`: no column found for `col_mo`, ignoring antibiotics set in `gram_negative` and `gram_positive`, and antimycotics set in `antifungal`") gramstain <- NA_character_ kingdom <- NA_character_ } else { x.mo <- as.mo(x[, col_mo, drop = TRUE]) gramstain <- mo_gramstain(x.mo, language = NULL) kingdom <- mo_kingdom(x.mo, language = NULL) } AMR_string <- function(x, values, name, filter, cols = cols) { if (is.null(values)) { return(rep(NA_character_, length(which(filter)))) } values_old_length <- length(values) values <- as.ab(values, flag_multiple_results = FALSE, info = FALSE) values <- cols[names(cols) %in% values] values_new_length <- length(values) if (values_new_length < values_old_length && any(filter, na.rm = TRUE) && message_not_thrown_before("key_antimicrobials", name)) { warning_( "in `key_antimicrobials()`: ", ifelse(values_new_length == 0, "No columns available ", paste0("Only using ", values_new_length, " out of ", values_old_length, " defined columns ") ), "as key antimicrobials for ", name, "s. See ?key_antimicrobials." ) } generate_antimcrobials_string(x[which(filter), c(universal, values), drop = FALSE]) } if (is.null(universal)) { universal <- character(0) } else { universal <- as.ab(universal, flag_multiple_results = FALSE, info = FALSE) universal <- cols[names(cols) %in% universal] } key_ab <- rep(NA_character_, nrow(x)) key_ab[which(gramstain == "Gram-negative")] <- AMR_string( x = x, values = gram_negative, name = "Gram-negative", filter = gramstain == "Gram-negative", cols = cols ) key_ab[which(gramstain == "Gram-positive")] <- AMR_string( x = x, values = gram_positive, name = "Gram-positive", filter = gramstain == "Gram-positive", cols = cols ) key_ab[which(kingdom == "Fungi")] <- AMR_string( x = x, values = antifungal, name = "antifungal", filter = kingdom == "Fungi", cols = cols ) # back-up - only use `universal` key_ab[which(is.na(key_ab))] <- AMR_string( x = x, values = character(0), name = "", filter = is.na(key_ab), cols = cols ) if (length(unique(key_ab)) == 1) { warning_("in `key_antimicrobials()`: no distinct key antibiotics determined.") } key_ab } #' @rdname key_antimicrobials #' @export all_antimicrobials <- function(x = NULL, only_sir_columns = FALSE, ...) { if (is_null_or_grouped_tbl(x)) { # when `x` is left blank, auto determine it (get_current_data() searches underlying data within call) # is also fix for using a grouped df as input (a dot as first argument) x <- tryCatch(get_current_data(arg_name = "x", call = -2), error = function(e) x) } meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0 meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) # force regular data.frame, not a tibble or data.table x <- as.data.frame(x, stringsAsFactors = FALSE) cols <- get_column_abx(x, only_sir_columns = only_sir_columns, info = FALSE, sort = FALSE, fn = "all_antimicrobials" ) generate_antimcrobials_string(x[, cols, drop = FALSE]) } generate_antimcrobials_string <- function(df) { if (NCOL(df) == 0) { return(rep("", NROW(df))) } if (NROW(df) == 0) { return(character(0)) } tryCatch( { do.call( paste0, lapply( as.list(df), function(x) { x <- toupper(as.character(x)) x[!x %in% c("S", "I", "R")] <- "." paste(x) } ) ) }, error = function(e) rep(strrep(".", NCOL(df)), NROW(df)) ) } #' @rdname key_antimicrobials #' @export antimicrobials_equal <- function(y, z, type = c("points", "keyantimicrobials"), ignore_I = TRUE, points_threshold = 2, ...) { meet_criteria(y, allow_class = "character") meet_criteria(z, allow_class = "character") stop_if(missing(type), "argument \"type\" is missing, with no default") meet_criteria(type, allow_class = "character", has_length = 1, is_in = c("points", "keyantimicrobials")) meet_criteria(ignore_I, allow_class = "logical", has_length = 1) meet_criteria(points_threshold, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) stop_ifnot(length(y) == length(z), "length of `y` and `z` must be equal") key2sir <- function(val) { val <- strsplit(val, "", fixed = TRUE)[[1L]] val.int <- rep(NA_real_, length(val)) val.int[val == "S"] <- 1 val.int[val == "I"] <- 2 val.int[val == "R"] <- 3 val.int } # only run on uniques uniq <- unique(c(y, z)) uniq_list <- lapply(uniq, key2sir) names(uniq_list) <- uniq y <- uniq_list[match(y, names(uniq_list))] z <- uniq_list[match(z, names(uniq_list))] determine_equality <- function(a, b, type, points_threshold, ignore_I) { if (length(a) != length(b)) { # incomparable, so not equal return(FALSE) } # ignore NAs on both sides NA_ind <- which(is.na(a) | is.na(b)) a[NA_ind] <- NA_real_ b[NA_ind] <- NA_real_ if (type == "points") { # count points for every single character: # - no change is 0 points # - I <-> S|R is 0.5 point # - S|R <-> R|S is 1 point # use the levels of as.sir (S = 1, I = 2, R = 3) # and divide by 2 (S = 0.5, I = 1, R = 1.5) (sum(abs(a - b), na.rm = TRUE) / 2) < points_threshold } else { if (ignore_I == TRUE) { ind <- which(a == 2 | b == 2) # since as.double(as.sir("I")) == 2 a[ind] <- NA_real_ b[ind] <- NA_real_ } all(a == b, na.rm = TRUE) } } out <- unlist(Map( f = determine_equality, y, z, MoreArgs = list( type = type, points_threshold = points_threshold, ignore_I = ignore_I ), USE.NAMES = FALSE )) out[is.na(y) | is.na(z)] <- NA out }
/scratch/gouwar.j/cran-all/cranData/AMR/R/key_antimicrobials.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Kurtosis of the Sample #' #' @description Kurtosis is a measure of the "tailedness" of the probability distribution of a real-valued random variable. A normal distribution has a kurtosis of 3 and a excess kurtosis of 0. #' @param x a vector of values, a [matrix] or a [data.frame] #' @param na.rm a [logical] to indicate whether `NA` values should be stripped before the computation proceeds #' @param excess a [logical] to indicate whether the *excess kurtosis* should be returned, defined as the kurtosis minus 3. #' @seealso [skewness()] #' @rdname kurtosis #' @export #' @examples #' kurtosis(rnorm(10000)) #' kurtosis(rnorm(10000), excess = TRUE) kurtosis <- function(x, na.rm = FALSE, excess = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) meet_criteria(excess, allow_class = "logical", has_length = 1) UseMethod("kurtosis") } #' @method kurtosis default #' @rdname kurtosis #' @export kurtosis.default <- function(x, na.rm = FALSE, excess = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) meet_criteria(excess, allow_class = "logical", has_length = 1) x <- as.vector(x) if (isTRUE(na.rm)) { x <- x[!is.na(x)] } n <- length(x) k <- n * sum((x - mean(x, na.rm = na.rm))^4, na.rm = na.rm) / (sum((x - mean(x, na.rm = na.rm))^2, na.rm = na.rm)^2) k - ifelse(excess, 3, 0) } #' @method kurtosis matrix #' @rdname kurtosis #' @export kurtosis.matrix <- function(x, na.rm = FALSE, excess = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) meet_criteria(excess, allow_class = "logical", has_length = 1) apply(x, 2, kurtosis.default, na.rm = na.rm, excess = excess) } #' @method kurtosis data.frame #' @rdname kurtosis #' @export kurtosis.data.frame <- function(x, na.rm = FALSE, excess = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) meet_criteria(excess, allow_class = "logical", has_length = 1) vapply(FUN.VALUE = double(1), x, kurtosis.default, na.rm = na.rm, excess = excess) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/kurtosis.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Vectorised Pattern Matching with Keyboard Shortcut #' #' Convenient wrapper around [grepl()] to match a pattern: `x %like% pattern`. It always returns a [`logical`] vector and is always case-insensitive (use `x %like_case% pattern` for case-sensitive matching). Also, `pattern` can be as long as `x` to compare items of each index in both vectors, or they both can have the same length to iterate over all cases. #' @param x a [character] vector where matches are sought, or an object which can be coerced by [as.character()] to a [character] vector. #' @param pattern a [character] vector containing regular expressions (or a [character] string for `fixed = TRUE`) to be matched in the given [character] vector. Coerced by [as.character()] to a [character] string if possible. #' @param ignore.case if `FALSE`, the pattern matching is *case sensitive* and if `TRUE`, case is ignored during matching. #' @return A [logical] vector #' @name like #' @rdname like #' @export #' @details #' These [like()] and `%like%`/`%unlike%` functions: #' * Are case-insensitive (use `%like_case%`/`%unlike_case%` for case-sensitive matching) #' * Support multiple patterns #' * Check if `pattern` is a valid regular expression and sets `fixed = TRUE` if not, to greatly improve speed (vectorised over `pattern`) #' * Always use compatibility with Perl unless `fixed = TRUE`, to greatly improve speed #' #' Using RStudio? The `%like%`/`%unlike%` functions can also be directly inserted in your code from the Addins menu and can have its own keyboard shortcut like `Shift+Ctrl+L` or `Shift+Cmd+L` (see menu `Tools` > `Modify Keyboard Shortcuts...`). If you keep pressing your shortcut, the inserted text will be iterated over `%like%` -> `%unlike%` -> `%like_case%` -> `%unlike_case%`. #' @source Idea from the [`like` function from the `data.table` package](https://github.com/Rdatatable/data.table/blob/ec1259af1bf13fc0c96a1d3f9e84d55d8106a9a4/R/like.R), although altered as explained in *Details*. #' @seealso [grepl()] #' @examples #' # data.table has a more limited version of %like%, so unload it: #' try(detach("package:data.table", unload = TRUE), silent = TRUE) #' #' a <- "This is a test" #' b <- "TEST" #' a %like% b #' b %like% a #' #' # also supports multiple patterns #' a <- c("Test case", "Something different", "Yet another thing") #' b <- c("case", "diff", "yet") #' a %like% b #' a %unlike% b #' #' a[1] %like% b #' a %like% b[1] #' #' \donttest{ #' # get isolates whose name start with 'Entero' (case-insensitive) #' example_isolates[which(mo_name() %like% "^entero"), ] #' #' if (require("dplyr")) { #' example_isolates %>% #' filter(mo_name() %like% "^ent") #' } #' } like <- function(x, pattern, ignore.case = TRUE) { meet_criteria(x, allow_NA = TRUE) meet_criteria(pattern, allow_NA = FALSE) meet_criteria(ignore.case, allow_class = "logical", has_length = 1) if (all(is.na(x))) { return(rep(FALSE, length(x))) } # set to fixed if no valid regex (vectorised) fixed <- !is_valid_regex(pattern) if (ignore.case == TRUE) { # set here, otherwise if fixed = TRUE, this warning will be thrown: argument `ignore.case = TRUE` will be ignored x <- tolower(x) pattern <- tolower(pattern) } if (is.factor(x)) { x <- as.character(x) } if (length(pattern) == 1) { grepl(pattern, x, ignore.case = FALSE, fixed = fixed, perl = !fixed) } else { if (length(x) == 1) { x <- rep(x, length(pattern)) } else if (length(pattern) != length(x)) { stop_( "arguments `x` and `pattern` must be of same length, or either one must be 1 ", "(`x` has length ", length(x), " and `pattern` has length ", length(pattern), ")" ) } unlist( Map( f = grepl, x = x, pattern = pattern, fixed = fixed, perl = !fixed, MoreArgs = list(ignore.case = FALSE), USE.NAMES = FALSE ) ) } } #' @rdname like #' @export "%like%" <- function(x, pattern) { like(x, pattern, ignore.case = TRUE) } #' @rdname like #' @export "%unlike%" <- function(x, pattern) { !like(x, pattern, ignore.case = TRUE) } #' @rdname like #' @export "%like_case%" <- function(x, pattern) { like(x, pattern, ignore.case = FALSE) } #' @rdname like #' @export "%unlike_case%" <- function(x, pattern) { !like(x, pattern, ignore.case = FALSE) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/like.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Determine Multidrug-Resistant Organisms (MDRO) #' #' Determine which isolates are multidrug-resistant organisms (MDRO) according to international, national and custom guidelines. #' @param x a [data.frame] with antibiotics columns, like `AMX` or `amox`. Can be left blank for automatic determination. #' @param guideline a specific guideline to follow, see sections *Supported international / national guidelines* and *Using Custom Guidelines* below. When left empty, the publication by Magiorakos *et al.* (see below) will be followed. #' @param ... in case of [custom_mdro_guideline()]: a set of rules, see section *Using Custom Guidelines* below. Otherwise: column name of an antibiotic, see section *Antibiotics* below. #' @param as_factor a [logical] to indicate whether the returned value should be an ordered [factor] (`TRUE`, default), or otherwise a [character] vector #' @inheritParams eucast_rules #' @param pct_required_classes minimal required percentage of antimicrobial classes that must be available per isolate, rounded down. For example, with the default guideline, 17 antimicrobial classes must be available for *S. aureus*. Setting this `pct_required_classes` argument to `0.5` (default) means that for every *S. aureus* isolate at least 8 different classes must be available. Any lower number of available classes will return `NA` for that isolate. #' @param combine_SI a [logical] to indicate whether all values of S and I must be merged into one, so resistance is only considered when isolates are R, not I. As this is the default behaviour of the [mdro()] function, it follows the redefinition by EUCAST about the interpretation of I (increased exposure) in 2019, see section 'Interpretation of S, I and R' below. When using `combine_SI = FALSE`, resistance is considered when isolates are R or I. #' @param verbose a [logical] to turn Verbose mode on and off (default is off). In Verbose mode, the 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. #' @inheritSection eucast_rules Antibiotics #' @details #' These functions are context-aware. This means that the `x` argument can be left blank if used inside a [data.frame] call, see *Examples*. #' #' For the `pct_required_classes` argument, values above 1 will be divided by 100. This is to support both fractions (`0.75` or `3/4`) and percentages (`75`). #' #' **Note:** Every test that involves the Enterobacteriaceae family, will internally be performed using its newly named *order* Enterobacterales, since the Enterobacteriaceae family has been taxonomically reclassified by Adeolu *et al.* in 2016. Before that, Enterobacteriaceae was the only family under the Enterobacteriales (with an i) order. All species under the old Enterobacteriaceae family are still under the new Enterobacterales (without an i) order, but divided into multiple families. The way tests are performed now by this [mdro()] function makes sure that results from before 2016 and after 2016 are identical. #' #' @section Supported International / National Guidelines: #' #' Currently supported guidelines are (case-insensitive): #' #' * `guideline = "CMI2012"` (default) #' #' Magiorakos AP, Srinivasan A *et al.* "Multidrug-resistant, extensively drug-resistant and pandrug-resistant bacteria: an international expert proposal for interim standard definitions for acquired resistance." Clinical Microbiology and Infection (2012) (\doi{10.1111/j.1469-0691.2011.03570.x}) #' #' * `guideline = "EUCAST3.3"` (or simply `guideline = "EUCAST"`) #' #' The European international guideline - EUCAST Expert Rules Version 3.3 "Intrinsic Resistance and Unusual Phenotypes" ([link](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2021/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.3_20211018.pdf)) #' #' * `guideline = "EUCAST3.2"` #' #' The European international guideline - EUCAST Expert Rules Version 3.2 "Intrinsic Resistance and Unusual Phenotypes" ([link](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2020/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.2_20200225.pdf)) #' #' * `guideline = "EUCAST3.1"` #' #' The European international guideline - EUCAST Expert Rules Version 3.1 "Intrinsic Resistance and Exceptional Phenotypes Tables" ([link](https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/Expert_rules_intrinsic_exceptional_V3.1.pdf)) #' #' * `guideline = "TB"` #' #' The international guideline for multi-drug resistant tuberculosis - World Health Organization "Companion handbook to the WHO guidelines for the programmatic management of drug-resistant tuberculosis" ([link](https://www.who.int/publications/i/item/9789241548809)) #' #' * `guideline = "MRGN"` #' #' The German national guideline - Mueller et al. (2015) Antimicrobial Resistance and Infection Control 4:7; \doi{10.1186/s13756-015-0047-6} #' #' * `guideline = "BRMO"` #' #' The Dutch national guideline - Rijksinstituut voor Volksgezondheid en Milieu "WIP-richtlijn BRMO (Bijzonder Resistente Micro-Organismen) (ZKH)" ([link](https://www.rivm.nl/wip-richtlijn-brmo-bijzonder-resistente-micro-organismen-zkh)) #' #' Please suggest your own (country-specific) guidelines by letting us know: <https://github.com/msberends/AMR/issues/new>. #' #' @section Using Custom Guidelines: #' #' Custom guidelines can be set with the [custom_mdro_guideline()] function. This is of great importance if you have custom rules to determine MDROs in your hospital, e.g., rules that are dependent on ward, state of contact isolation or other variables in your data. #' #' If you are familiar with the [`case_when()`][dplyr::case_when()] function of the `dplyr` package, you will recognise the input method to set your own rules. Rules must be set using what \R considers to be the 'formula notation'. The rule is written *before* the tilde (`~`) and the consequence of the rule is written *after* the tilde: #' #' ``` #' custom <- custom_mdro_guideline(CIP == "R" & age > 60 ~ "Elderly Type A", #' ERY == "R" & age > 60 ~ "Elderly Type B") #' ``` #' #' If a row/an isolate matches the first rule, the value after the first `~` (in this case *'Elderly Type A'*) will be set as MDRO value. Otherwise, the second rule will be tried and so on. The number of rules is unlimited. #' #' You can print the rules set in the console for an overview. Colours will help reading it if your console supports colours. #' #' ``` #' custom #' #> A set of custom MDRO rules: #' #> 1. CIP is "R" and age is higher than 60 -> Elderly Type A #' #> 2. ERY is "R" and age is higher than 60 -> Elderly Type B #' #> 3. Otherwise -> Negative #' #> #' #> Unmatched rows will return NA. #' ``` #' #' The outcome of the function can be used for the `guideline` argument in the [mdro()] function: #' #' ``` #' x <- mdro(example_isolates, #' guideline = custom) #' table(x) #' #> Negative Elderly Type A Elderly Type B #' #> 1070 198 732 #' ``` #' #' Rules can also be combined with other custom rules by using [c()]: #' #' ``` #' x <- mdro(example_isolates, #' guideline = c(custom, #' custom_mdro_guideline(ERY == "R" & age > 50 ~ "Elderly Type C"))) #' table(x) #' #> Negative Elderly Type A Elderly Type B Elderly Type C #' #> 961 198 732 109 #' ``` #' #' The rules set (the `custom` object in this case) could be exported to a shared file location using [saveRDS()] if you collaborate with multiple users. The custom rules set could then be imported using [readRDS()]. #' @inheritSection as.sir Interpretation of SIR #' @return #' - CMI 2012 paper - function [mdr_cmi2012()] or [mdro()]:\cr #' Ordered [factor] with levels `Negative` < `Multi-drug-resistant (MDR)` < `Extensively drug-resistant (XDR)` < `Pandrug-resistant (PDR)` #' - TB guideline - function [mdr_tb()] or [`mdro(..., guideline = "TB")`][mdro()]:\cr #' Ordered [factor] with levels `Negative` < `Mono-resistant` < `Poly-resistant` < `Multi-drug-resistant` < `Extensively drug-resistant` #' - German guideline - function [mrgn()] or [`mdro(..., guideline = "MRGN")`][mdro()]:\cr #' Ordered [factor] with levels `Negative` < `3MRGN` < `4MRGN` #' - Everything else, except for custom guidelines:\cr #' Ordered [factor] with levels `Negative` < `Positive, unconfirmed` < `Positive`. The value `"Positive, unconfirmed"` means that, according to the guideline, it is not entirely sure if the isolate is multi-drug resistant and this should be confirmed with additional (e.g. molecular) tests #' @rdname mdro #' @aliases MDR XDR PDR BRMO 3MRGN 4MRGN #' @export #' @source #' See the supported guidelines above for the [list] of publications used for this function. #' @examples #' out <- mdro(example_isolates, guideline = "EUCAST") #' str(out) #' table(out) #' #' out <- mdro(example_isolates, #' guideline = custom_mdro_guideline( #' AMX == "R" ~ "Custom MDRO 1", #' VAN == "R" ~ "Custom MDRO 2" #' ) #' ) #' table(out) #' #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' mdro() %>% #' table() #' #' # no need to define `x` when used inside dplyr verbs: #' example_isolates %>% #' mutate(MDRO = mdro()) %>% #' pull(MDRO) %>% #' table() #' } #' } mdro <- function(x = NULL, guideline = "CMI2012", col_mo = NULL, info = interactive(), pct_required_classes = 0.5, combine_SI = TRUE, verbose = FALSE, only_sir_columns = FALSE, ...) { if (is_null_or_grouped_tbl(x)) { # when `x` is left blank, auto determine it (get_current_data() searches underlying data within call) # is also a fix for using a grouped df as input (i.e., a dot as first argument) x <- tryCatch(get_current_data(arg_name = "x", call = -2), error = function(e) x) } meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0 meet_criteria(guideline, allow_class = c("list", "character"), allow_NULL = TRUE) if (!is.list(guideline)) { meet_criteria(guideline, allow_class = "character", has_length = 1, allow_NULL = TRUE) } meet_criteria(col_mo, allow_class = "character", has_length = 1, is_in = colnames(x), allow_NULL = TRUE) meet_criteria(info, allow_class = "logical", has_length = 1) meet_criteria(pct_required_classes, allow_class = "numeric", has_length = 1) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(verbose, allow_class = "logical", has_length = 1) if ("only_rsi_columns" %in% names(list(...))) { deprecation_warning("only_rsi_columns", "only_sir_columns", is_function = FALSE) only_sir_columns <- list(...)$only_rsi_columns } meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) if (!any(is_sir_eligible(x))) { stop_("There were no possible SIR columns found in the data set. Transform columns with `as.sir()` for valid antimicrobial interpretations.") } info.bak <- info # don't throw info's more than once per call if (isTRUE(info)) { info <- message_not_thrown_before("mdro") } if (interactive() && isTRUE(verbose) && isTRUE(info)) { 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.:", "\ndata <- mdro(data, verbose = TRUE)\n\nDo you want to continue?" ) showQuestion <- import_fn("showQuestion", "rstudioapi", error_on_fail = FALSE) if (!is.null(showQuestion)) { q_continue <- showQuestion("Using verbose = TRUE with mdro()", txt) } else { q_continue <- utils::menu(choices = c("OK", "Cancel"), graphics = FALSE, title = txt) } if (q_continue %in% c(FALSE, 2)) { message_("Cancelled, returning original data", add_fn = font_red, as_note = FALSE) return(x) } } group_msg <- "" if (isTRUE(info.bak)) { # print group name if used in dplyr::group_by() cur_group <- import_fn("cur_group", "dplyr", error_on_fail = FALSE) if (!is.null(cur_group)) { group_df <- tryCatch(cur_group(), error = function(e) data.frame()) if (NCOL(group_df) > 0) { # transform factors to characters group <- vapply(FUN.VALUE = character(1), group_df, function(x) { if (is.numeric(x)) { format(x) } else if (is.logical(x)) { as.character(x) } else { paste0('"', x, '"') } }) group_msg <- paste0("\nGroup: ", paste0(names(group), " = ", group, collapse = ", "), "\n") } } } # force regular [data.frame], not a tibble or data.table x <- as.data.frame(x, stringsAsFactors = FALSE) if (pct_required_classes > 1) { # allow pct_required_classes = 75 -> pct_required_classes = 0.75 pct_required_classes <- pct_required_classes / 100 } guideline.bak <- guideline if (is.list(guideline)) { # Custom MDRO guideline --------------------------------------------------- stop_ifnot(inherits(guideline, "custom_mdro_guideline"), "use `custom_mdro_guideline()` to create custom guidelines") if (isTRUE(info)) { txt <- paste0( "Determining MDROs based on custom rules", ifelse(isTRUE(attributes(guideline)$as_factor), paste0(", resulting in factor levels: ", paste0(attributes(guideline)$values, collapse = " < ")), "" ), "." ) txt <- word_wrap(txt) cat(txt, "\n", sep = "") } x <- run_custom_mdro_guideline(df = x, guideline = guideline, info = info) if (isTRUE(info.bak)) { cat(group_msg) if (sum(!is.na(x$MDRO)) == 0) { cat(word_wrap(font_bold(paste0("=> Found 0 MDROs since no isolates are covered by the custom guideline")))) } else { cat(word_wrap(font_bold(paste0( "=> Found ", sum(x$MDRO != "Negative", na.rm = TRUE), " custom defined MDROs out of ", sum(!is.na(x$MDRO)), " isolates (", trimws(percentage(sum(x$MDRO != "Negative", na.rm = TRUE) / sum(!is.na(x$MDRO)))), ")\n" )))) } } if (isTRUE(verbose)) { return(x[, c( "row_number", "MDRO", "reason", "columns_nonsusceptible" )]) } else { return(x$MDRO) } } guideline <- tolower(gsub("[^a-zA-Z0-9.]+", "", guideline)) if (is.null(guideline)) { # default to the paper by Magiorakos et al. (2012) guideline <- "cmi2012" } if (guideline == "eucast") { # turn into latest EUCAST guideline guideline <- "eucast3.3" } if (guideline == "nl") { guideline <- "brmo" } if (guideline == "de") { guideline <- "mrgn" } stop_ifnot( guideline %in% c("brmo", "mrgn", "eucast3.1", "eucast3.2", "eucast3.3", "tb", "cmi2012"), "invalid guideline: ", guideline.bak ) guideline <- list(code = guideline) # try to find columns based on type # -- mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = info) } if (is.null(col_mo) && guideline$code == "tb") { message_( "No column found as input for `col_mo`, ", font_bold(paste0("assuming all rows contain ", font_italic("Mycobacterium tuberculosis"), ".")) ) x$mo <- as.mo("Mycobacterium tuberculosis", keep_synonyms = TRUE) col_mo <- "mo" } stop_if(is.null(col_mo), "`col_mo` must be set") if (guideline$code == "cmi2012") { guideline$name <- "Multidrug-resistant, extensively drug-resistant and pandrug-resistant bacteria: an international expert proposal for interim standard definitions for acquired resistance." guideline$author <- "Magiorakos AP, Srinivasan A, Carey RB, ..., Vatopoulos A, Weber JT, Monnet DL" guideline$version <- NA guideline$source_url <- paste0("Clinical Microbiology and Infection 18:3, 2012; ", font_url("https://doi.org/10.1111/j.1469-0691.2011.03570.x", "doi: 10.1111/j.1469-0691.2011.03570.x")) guideline$type <- "MDRs/XDRs/PDRs" } else if (guideline$code == "eucast3.1") { guideline$name <- "EUCAST Expert Rules, \"Intrinsic Resistance and Exceptional Phenotypes Tables\"" guideline$author <- "EUCAST (European Committee on Antimicrobial Susceptibility Testing)" guideline$version <- "3.1, 2016" guideline$source_url <- font_url("https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/Expert_rules_intrinsic_exceptional_V3.1.pdf", "Direct download") guideline$type <- "EUCAST Exceptional Phenotypes" } else if (guideline$code == "eucast3.2") { guideline$name <- "EUCAST Expert Rules, \"Intrinsic Resistance and Unusual Phenotypes\"" guideline$author <- "EUCAST (European Committee on Antimicrobial Susceptibility Testing)" guideline$version <- "3.2, February 2020" guideline$source_url <- font_url("https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2020/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.2_20200225.pdf", "Direct download") guideline$type <- "EUCAST Unusual Phenotypes" } else if (guideline$code == "eucast3.3") { guideline$name <- "EUCAST Expert Rules, \"Intrinsic Resistance and Unusual Phenotypes\"" guideline$author <- "EUCAST (European Committee on Antimicrobial Susceptibility Testing)" guideline$version <- "3.3, October 2021" guideline$source_url <- font_url("https://www.eucast.org/fileadmin/src/media/PDFs/EUCAST_files/Expert_Rules/2021/Intrinsic_Resistance_and_Unusual_Phenotypes_Tables_v3.3_20211018.pdf", "Direct download") guideline$type <- "EUCAST Unusual Phenotypes" } else if (guideline$code == "tb") { guideline$name <- "Companion handbook to the WHO guidelines for the programmatic management of drug-resistant tuberculosis" guideline$author <- "WHO (World Health Organization)" guideline$version <- "WHO/HTM/TB/2014.11, 2014" guideline$source_url <- font_url("https://www.who.int/publications/i/item/9789241548809", "Direct download") guideline$type <- "MDR-TB's" # support per country: } else if (guideline$code == "mrgn") { guideline$name <- "Cross-border comparison of the Dutch and German guidelines on multidrug-resistant Gram-negative microorganisms" guideline$author <- "M\u00fcller J, Voss A, K\u00f6ck R, ..., Kern WV, Wendt C, Friedrich AW" guideline$version <- NA guideline$source_url <- paste0("Antimicrobial Resistance and Infection Control 4:7, 2015; ", font_url("https://doi.org/10.1186/s13756-015-0047-6", "doi: 10.1186/s13756-015-0047-6")) guideline$type <- "MRGNs" } else if (guideline$code == "brmo") { guideline$name <- "WIP-Richtlijn Bijzonder Resistente Micro-organismen (BRMO)" guideline$author <- "RIVM (Rijksinstituut voor de Volksgezondheid)" guideline$version <- "Revision as of December 2017" guideline$source_url <- font_url("https://www.rivm.nl/Documenten_en_publicaties/Professioneel_Praktisch/Richtlijnen/Infectieziekten/WIP_Richtlijnen/WIP_Richtlijnen/Ziekenhuizen/WIP_richtlijn_BRMO_Bijzonder_Resistente_Micro_Organismen_ZKH", "Direct download") guideline$type <- "BRMOs" } else { stop("This guideline is currently unsupported: ", guideline$code, call. = FALSE) } if (guideline$code == "cmi2012") { cols_ab <- get_column_abx( x = x, soft_dependencies = c( # [table] 1 (S aureus) "GEN", "RIF", "CPT", "OXA", "CIP", "MFX", "SXT", "FUS", "VAN", "TEC", "TLV", "TGC", "CLI", "DAP", "ERY", "LNZ", "CHL", "FOS", "QDA", "TCY", "DOX", "MNO", # [table] 2 (Enterococcus) "GEH", "STH", "IPM", "MEM", "DOR", "CIP", "LVX", "MFX", "VAN", "TEC", "TGC", "DAP", "LNZ", "AMP", "QDA", "DOX", "MNO", # [table] 3 (Enterobacteriaceae) "GEN", "TOB", "AMK", "NET", "CPT", "TCC", "TZP", "ETP", "IPM", "MEM", "DOR", "CZO", "CXM", "CTX", "CAZ", "FEP", "FOX", "CTT", "CIP", "SXT", "TGC", "ATM", "AMP", "AMC", "SAM", "CHL", "FOS", "COL", "TCY", "DOX", "MNO", # [table] 4 (Pseudomonas) "GEN", "TOB", "AMK", "NET", "IPM", "MEM", "DOR", "CAZ", "FEP", "CIP", "LVX", "TCC", "TZP", "ATM", "FOS", "COL", "PLB", # [table] 5 (Acinetobacter) "GEN", "TOB", "AMK", "NET", "IPM", "MEM", "DOR", "CIP", "LVX", "TZP", "TCC", "CTX", "CRO", "CAZ", "FEP", "SXT", "SAM", "COL", "PLB", "TCY", "DOX", "MNO" ), verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } else if (guideline$code == "eucast3.2") { cols_ab <- get_column_abx( x = x, soft_dependencies = c("AMP", "AMX", "CIP", "DAL", "DAP", "ERV", "FDX", "GEN", "LNZ", "MEM", "MTR", "OMC", "ORI", "PEN", "QDA", "RIF", "TEC", "TGC", "TLV", "TOB", "TZD", "VAN"), verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } else if (guideline$code == "eucast3.3") { cols_ab <- get_column_abx( x = x, soft_dependencies = c("AMP", "AMX", "CIP", "DAL", "DAP", "ERV", "FDX", "GEN", "LNZ", "MEM", "MTR", "OMC", "ORI", "PEN", "QDA", "RIF", "TEC", "TGC", "TLV", "TOB", "TZD", "VAN"), verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } else if (guideline$code == "tb") { cols_ab <- get_column_abx( x = x, soft_dependencies = c("CAP", "ETH", "GAT", "INH", "PZA", "RIF", "RIB", "RFP"), verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } else if (guideline$code == "mrgn") { cols_ab <- get_column_abx( x = x, soft_dependencies = c("PIP", "CTX", "CAZ", "IPM", "MEM", "CIP"), verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } else { cols_ab <- get_column_abx( x = x, verbose = verbose, info = info, only_sir_columns = only_sir_columns, fn = "mdro", ... ) } if (!"AMP" %in% names(cols_ab) && "AMX" %in% names(cols_ab)) { # ampicillin column is missing, but amoxicillin is available if (isTRUE(info)) { message_("Using column '", cols_ab[names(cols_ab) == "AMX"], "' as input for ampicillin since many EUCAST rules depend on it.") } cols_ab <- c(cols_ab, c(AMP = unname(cols_ab[names(cols_ab) == "AMX"]))) } # nolint start AMC <- cols_ab["AMC"] AMK <- cols_ab["AMK"] AMP <- cols_ab["AMP"] AMX <- cols_ab["AMX"] ATM <- cols_ab["ATM"] AZL <- cols_ab["AZL"] AZM <- cols_ab["AZM"] BPR <- cols_ab["BPR"] CAC <- cols_ab["CAC"] CAT <- cols_ab["CAT"] CAZ <- cols_ab["CAZ"] CCV <- cols_ab["CCV"] CDR <- cols_ab["CDR"] CDZ <- cols_ab["CDZ"] CEC <- cols_ab["CEC"] CED <- cols_ab["CED"] CEI <- cols_ab["CEI"] CEP <- cols_ab["CEP"] CFM <- cols_ab["CFM"] CFM1 <- cols_ab["CFM1"] CFP <- cols_ab["CFP"] CFR <- cols_ab["CFR"] CFS <- cols_ab["CFS"] CHL <- cols_ab["CHL"] CID <- cols_ab["CID"] CIP <- cols_ab["CIP"] CLI <- cols_ab["CLI"] CLR <- cols_ab["CLR"] CMX <- cols_ab["CMX"] CMZ <- cols_ab["CMZ"] CND <- cols_ab["CND"] COL <- cols_ab["COL"] CPD <- cols_ab["CPD"] CPM <- cols_ab["CPM"] CPO <- cols_ab["CPO"] CPR <- cols_ab["CPR"] CPT <- cols_ab["CPT"] CRD <- cols_ab["CRD"] CRO <- cols_ab["CRO"] CSL <- cols_ab["CSL"] CTB <- cols_ab["CTB"] CTF <- cols_ab["CTF"] CTL <- cols_ab["CTL"] CTT <- cols_ab["CTT"] CTX <- cols_ab["CTX"] CTZ <- cols_ab["CTZ"] CXM <- cols_ab["CXM"] CZD <- cols_ab["CZD"] CZO <- cols_ab["CZO"] CZX <- cols_ab["CZX"] DAL <- cols_ab["DAL"] DAP <- cols_ab["DAP"] DIT <- cols_ab["DIT"] DIZ <- cols_ab["DIZ"] DOR <- cols_ab["DOR"] DOX <- cols_ab["DOX"] ENX <- cols_ab["ENX"] ERV <- cols_ab["ERV"] ERY <- cols_ab["ERY"] ETP <- cols_ab["ETP"] FDX <- cols_ab["FDX"] FEP <- cols_ab["FEP"] FLC <- cols_ab["FLC"] FLE <- cols_ab["FLE"] FOS <- cols_ab["FOS"] FOX <- cols_ab["FOX"] FUS <- cols_ab["FUS"] GAT <- cols_ab["GAT"] GEH <- cols_ab["GEH"] GEM <- cols_ab["GEM"] GEN <- cols_ab["GEN"] GRX <- cols_ab["GRX"] HAP <- cols_ab["HAP"] IPM <- cols_ab["IPM"] KAN <- cols_ab["KAN"] LEX <- cols_ab["LEX"] LIN <- cols_ab["LIN"] LNZ <- cols_ab["LNZ"] LOM <- cols_ab["LOM"] LOR <- cols_ab["LOR"] LTM <- cols_ab["LTM"] LVX <- cols_ab["LVX"] MAN <- cols_ab["MAN"] MEM <- cols_ab["MEM"] MEV <- cols_ab["MEV"] MEZ <- cols_ab["MEZ"] MFX <- cols_ab["MFX"] MNO <- cols_ab["MNO"] MTR <- cols_ab["MTR"] NAL <- cols_ab["NAL"] NEO <- cols_ab["NEO"] NET <- cols_ab["NET"] NIT <- cols_ab["NIT"] NOR <- cols_ab["NOR"] NOV <- cols_ab["NOV"] OFX <- cols_ab["OFX"] OMC <- cols_ab["OMC"] ORI <- cols_ab["ORI"] OXA <- cols_ab["OXA"] PAZ <- cols_ab["PAZ"] PEF <- cols_ab["PEF"] PEN <- cols_ab["PEN"] PIP <- cols_ab["PIP"] PLB <- cols_ab["PLB"] PRI <- cols_ab["PRI"] PRU <- cols_ab["PRU"] QDA <- cols_ab["QDA"] RFL <- cols_ab["RFL"] RID <- cols_ab["RID"] RIF <- cols_ab["RIF"] RXT <- cols_ab["RXT"] SAM <- cols_ab["SAM"] SIS <- cols_ab["SIS"] SPT <- cols_ab["SPT"] SPX <- cols_ab["SPX"] STH <- cols_ab["STH"] SXT <- cols_ab["SXT"] TCC <- cols_ab["TCC"] TCY <- cols_ab["TCY"] TEC <- cols_ab["TEC"] TGC <- cols_ab["TGC"] TIC <- cols_ab["TIC"] TLV <- cols_ab["TLV"] TMP <- cols_ab["TMP"] TMX <- cols_ab["TMX"] TOB <- cols_ab["TOB"] TVA <- cols_ab["TVA"] TZD <- cols_ab["TZD"] TZP <- cols_ab["TZP"] VAN <- cols_ab["VAN"] # additional for TB CAP <- cols_ab["CAP"] ETH <- cols_ab["ETH"] GAT <- cols_ab["GAT"] INH <- cols_ab["INH"] PZA <- cols_ab["PZA"] RIF <- cols_ab["RIF"] RIB <- cols_ab["RIB"] RFP <- cols_ab["RFP"] abx_tb <- c(CAP, ETH, GAT, INH, PZA, RIF, RIB, RFP) abx_tb <- abx_tb[!is.na(abx_tb)] stop_if(guideline$code == "tb" & length(abx_tb) == 0, "no antimycobacterials found in data set") # nolint end if (isTRUE(combine_SI)) { search_result <- "R" } else { search_result <- c("R", "I") } if (isTRUE(info)) { if (isTRUE(combine_SI)) { cat(font_red("\nOnly results with 'R' are considered as resistance. Use `combine_SI = FALSE` to also consider 'I' as resistance.\n")) } else { cat(font_red("\nResults with 'R' or 'I' are considered as resistance. Use `combine_SI = TRUE` to only consider 'R' as resistance.\n")) } cat("\n", word_wrap("Determining multidrug-resistant organisms (MDRO), according to:"), "\n", word_wrap(paste0(font_bold("Guideline: "), font_italic(guideline$name)), extra_indent = 11, as_note = FALSE), "\n", word_wrap(paste0(font_bold("Author(s): "), guideline$author), extra_indent = 11, as_note = FALSE), "\n", ifelse(!is.na(guideline$version), paste0(word_wrap(paste0(font_bold("Version: "), guideline$version), extra_indent = 11, as_note = FALSE), "\n"), "" ), paste0(font_bold("Source: "), guideline$source_url), "\n\n", sep = "" ) } ab_missing <- function(ab) { isTRUE(ab %in% c(NULL, NA)) | length(ab) == 0 } ab_NA <- function(x) { x[!is.na(x)] } try_ab <- function(expr) { out <- tryCatch(expr, error = function(e) FALSE) out[is.na(out)] <- FALSE out } # antibiotic classes # nolint start aminoglycosides <- c(TOB, GEN) cephalosporins <- c(CDZ, CAC, CEC, CFR, RID, MAN, CTZ, CZD, CZO, CDR, DIT, FEP, CAT, CFM, CMX, CMZ, DIZ, CID, CFP, CSL, CND, CTX, CTT, CTF, FOX, CPM, CPO, CPD, CPR, CRD, CFS, CPT, CAZ, CCV, CTL, CTB, CZX, BPR, CFM1, CEI, CRO, CXM, LEX, CEP, HAP, CED, LTM, LOR) cephalosporins_1st <- c(CAC, CFR, RID, CTZ, CZD, CZO, CRD, CTL, LEX, CEP, HAP, CED) cephalosporins_2nd <- c(CEC, MAN, CMZ, CID, CND, CTT, CTF, FOX, CPR, CXM, LOR) cephalosporins_3rd <- c(CDZ, CDR, DIT, CAT, CFM, CMX, DIZ, CFP, CSL, CTX, CPM, CPD, CFS, CAZ, CCV, CTB, CZX, CRO, LTM) carbapenems <- c(DOR, ETP, IPM, MEM, MEV) fluoroquinolones <- c(CIP, ENX, FLE, GAT, GEM, GRX, LVX, LOM, MFX, NOR, OFX, PAZ, PEF, PRU, RFL, SPX, TMX, TVA) # nolint end # helper function for editing the table trans_tbl <- function(to, rows, cols, any_all) { cols <- cols[!ab_missing(cols)] cols <- cols[!is.na(cols)] if (length(rows) > 0 && length(cols) > 0) { x[, cols] <- as.data.frame( lapply( x[, cols, drop = FALSE], function(col) as.sir(col) ), stringsAsFactors = FALSE ) x[rows, "columns_nonsusceptible"] <<- vapply( FUN.VALUE = character(1), rows, function(row, group_vct = cols) { cols_nonsus <- vapply( FUN.VALUE = logical(1), x[row, group_vct, drop = FALSE], function(y) y %in% search_result ) paste( sort(c( unlist(strsplit(x[row, "columns_nonsusceptible", drop = TRUE], ", ", fixed = TRUE)), names(cols_nonsus)[cols_nonsus] )), collapse = ", " ) } ) if (any_all == "any") { search_function <- any } else if (any_all == "all") { search_function <- all } x_transposed <- as.list(as.data.frame(t(x[, cols, drop = FALSE]), stringsAsFactors = FALSE )) rows_affected <- vapply( FUN.VALUE = logical(1), x_transposed, function(y) search_function(y %in% search_result, na.rm = TRUE) ) rows_affected <- x[which(rows_affected), "row_number", drop = TRUE] rows_to_change <- rows[rows %in% rows_affected] x[rows_to_change, "MDRO"] <<- to x[rows_to_change, "reason"] <<- paste0( any_all, " of the required antibiotics ", ifelse(any_all == "any", "is", "are"), " R", ifelse(!isTRUE(combine_SI), " or I", "") ) } } trans_tbl2 <- function(txt, rows, lst) { if (isTRUE(info)) { message_(txt, "...", appendLF = FALSE, as_note = FALSE) } if (length(rows) > 0) { # function specific for the CMI paper of 2012 (Magiorakos et al.) lst_vector <- unlist(lst)[!is.na(unlist(lst))] # keep only unique ones: lst_vector <- lst_vector[!duplicated(paste(lst_vector, names(lst_vector)))] x[, lst_vector] <- as.data.frame( lapply( x[, lst_vector, drop = FALSE], function(col) as.sir(col) ), stringsAsFactors = FALSE ) x[rows, "classes_in_guideline"] <<- length(lst) x[rows, "classes_available"] <<- vapply( FUN.VALUE = double(1), rows, function(row, group_tbl = lst) { sum(vapply( FUN.VALUE = logical(1), group_tbl, function(group) any(unlist(x[row, group[!is.na(group)], drop = TRUE]) %in% c("S", "I", "R")) )) } ) if (isTRUE(verbose)) { x[rows, "columns_nonsusceptible"] <<- vapply( FUN.VALUE = character(1), rows, function(row, group_vct = lst_vector) { cols_nonsus <- vapply(FUN.VALUE = logical(1), x[row, group_vct, drop = FALSE], function(y) y %in% search_result) paste(sort(names(cols_nonsus)[cols_nonsus]), collapse = ", ") } ) } x[rows, "classes_affected"] <<- vapply( FUN.VALUE = double(1), rows, function(row, group_tbl = lst) { sum( vapply( FUN.VALUE = logical(1), group_tbl, function(group) { any(unlist(x[row, group[!is.na(group)], drop = TRUE]) %in% search_result, na.rm = TRUE) } ), na.rm = TRUE ) } ) # for PDR; all drugs are R (or I if combine_SI = FALSE) x_transposed <- as.list(as.data.frame(t(x[rows, lst_vector, drop = FALSE]), stringsAsFactors = FALSE )) row_filter <- vapply(FUN.VALUE = logical(1), x_transposed, function(y) all(y %in% search_result, na.rm = TRUE)) x[which(row_filter), "classes_affected"] <<- 999 } if (isTRUE(info)) { message_(" OK.", add_fn = list(font_green, font_bold), as_note = FALSE) } } x[, col_mo] <- as.mo(as.character(x[, col_mo, drop = TRUE])) # rename col_mo to prevent interference with joined columns colnames(x)[colnames(x) == col_mo] <- ".col_mo" col_mo <- ".col_mo" # join to microorganisms data set x <- left_join_microorganisms(x, by = col_mo) x$MDRO <- ifelse(!is.na(x$genus), 1, NA_integer_) x$row_number <- seq_len(nrow(x)) x$reason <- paste0("not covered by ", toupper(guideline$code), " guideline") x$columns_nonsusceptible <- "" if (guideline$code == "cmi2012") { # CMI, 2012 --------------------------------------------------------------- # Non-susceptible = R and I # (see header 'Approaches to Creating Definitions for MDR, XDR and PDR' in paper) # take amoxicillin if ampicillin is unavailable if (is.na(AMP) && !is.na(AMX)) { if (isTRUE(verbose)) { message_("Filling ampicillin (AMP) results with amoxicillin (AMX) results") } AMP <- AMX } # take ceftriaxone if cefotaxime is unavailable and vice versa if (is.na(CRO) && !is.na(CTX)) { if (isTRUE(verbose)) { message_("Filling ceftriaxone (CRO) results with cefotaxime (CTX) results") } CRO <- CTX } if (is.na(CTX) && !is.na(CRO)) { if (isTRUE(verbose)) { message_("Filling cefotaxime (CTX) results with ceftriaxone (CRO) results") } CTX <- CRO } # intrinsic resistant must not be considered for the determination of MDR, # so let's just remove them, meticulously following the paper x[which(x$genus == "Enterococcus" & x$species == "faecium"), ab_NA(IPM)] <- NA x[which(x$genus == "Enterococcus" & x$species == "faecalis"), ab_NA(QDA)] <- NA x[which((x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii")), ab_NA(c(GEN, TOB, NET))] <- NA x[which(x$genus == "Escherichia" & x$species == "hermannii"), ab_NA(c(TCC, TZP))] <- NA x[which((x$genus == "Citrobacter" & x$species == "freundii") | (x$genus == "Enterobacter" & x$species == "aerogenes") | (x$genus == "Klebsiella" & x$species == "aerogenes") # new name (2017) | (x$genus == "Enterobacter" & x$species == "cloacae") | (x$genus == "Hafnia" & x$species == "alvei") | (x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(CZO)] <- NA x[which((x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(CXM)] <- NA x[which((x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "mirabilis") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii")), ab_NA(TGC)] <- NA x[which((x$genus == "Citrobacter" & x$species == "koseri") | (x$genus == "Citrobacter" & x$species == "freundii") | (x$genus == "Enterobacter" & x$species == "aerogenes") | (x$genus == "Klebsiella" & x$species == "aerogenes") # new name (2017) | (x$genus == "Enterobacter" & x$species == "cloacae") | (x$genus == "Escherichia" & x$species == "hermannii") | (x$genus == "Hafnia" & x$species == "alvei") | (x$genus == "Klebsiella") | (x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(AMP)] <- NA x[which((x$genus == "Citrobacter" & x$species == "freundii") | (x$genus == "Enterobacter" & x$species == "aerogenes") | (x$genus == "Klebsiella" & x$species == "aerogenes") # new name (2017) | (x$genus == "Enterobacter" & x$species == "cloacae") | (x$genus == "Hafnia" & x$species == "alvei") | (x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(AMC)] <- NA x[which((x$genus == "Citrobacter" & x$species == "freundii") | (x$genus == "Citrobacter" & x$species == "koseri") | (x$genus == "Enterobacter" & x$species == "aerogenes") | (x$genus == "Klebsiella" & x$species == "aerogenes") # new name (2017) | (x$genus == "Enterobacter" & x$species == "cloacae") | (x$genus == "Hafnia" & x$species == "alvei") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(SAM)] <- NA x[which((x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "mirabilis") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii") | (x$genus == "Serratia" & x$species == "marcescens")), ab_NA(COL)] <- NA x[which((x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "mirabilis") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii")), ab_NA(TCY)] <- NA x[which((x$genus == "Morganella" & x$species == "morganii") | (x$genus == "Proteus" & x$species == "penneri") | (x$genus == "Proteus" & x$species == "vulgaris") | (x$genus == "Providencia" & x$species == "rettgeri") | (x$genus == "Providencia" & x$species == "stuartii")), ab_NA(c(DOX, MNO))] <- NA x$classes_in_guideline <- NA_integer_ x$classes_available <- NA_integer_ x$classes_affected <- NA_integer_ # now add the MDR levels to the data trans_tbl( 2, which(x$genus == "Staphylococcus" & x$species == "aureus"), c(OXA, FOX), "any" ) trans_tbl2( paste("Table 1 -", font_italic("Staphylococcus aureus")), which(x$genus == "Staphylococcus" & x$species == "aureus"), list( GEN, RIF, CPT, c(OXA, FOX), c(CIP, MFX), SXT, FUS, c(VAN, TEC, TLV), TGC, CLI, DAP, ERY, LNZ, CHL, FOS, QDA, c(TCY, DOX, MNO) ) ) trans_tbl2( paste("Table 2 -", font_italic("Enterococcus"), "spp."), which(x$genus == "Enterococcus"), list( GEH, STH, c(IPM, MEM, DOR), c(CIP, LVX, MFX), c(VAN, TEC), TGC, DAP, LNZ, AMP, QDA, c(DOX, MNO) ) ) trans_tbl2( paste0("Table 3 - ", font_italic("Enterobacteriaceae")), # this new order was previously 'Enterobacteriales' and contained only the family 'Enterobacteriaceae': which(x$order == "Enterobacterales"), list( c(GEN, TOB, AMK, NET), CPT, c(TCC, TZP), c(ETP, IPM, MEM, DOR), CZO, CXM, c(CTX, CAZ, FEP), c(FOX, CTT), CIP, SXT, TGC, ATM, AMP, c(AMC, SAM), CHL, FOS, COL, c(TCY, DOX, MNO) ) ) trans_tbl2( paste("Table 4 -", font_italic("Pseudomonas aeruginosa")), which(x$genus == "Pseudomonas" & x$species == "aeruginosa"), list( c(GEN, TOB, AMK, NET), c(IPM, MEM, DOR), c(CAZ, FEP), c(CIP, LVX), c(TCC, TZP), ATM, FOS, c(COL, PLB) ) ) trans_tbl2( paste("Table 5 -", font_italic("Acinetobacter"), "spp."), which(x$genus == "Acinetobacter"), list( c(GEN, TOB, AMK, NET), c(IPM, MEM, DOR), c(CIP, LVX), c(TZP, TCC), c(CTX, CRO, CAZ, FEP), SXT, SAM, c(COL, PLB), c(TCY, DOX, MNO) ) ) # now set MDROs: # MDR (=2): >=3 classes affected x[which(x$classes_affected >= 3), "MDRO"] <- 2 if (isTRUE(verbose)) { x[which(x$classes_affected >= 3), "reason"] <- paste0( "at least 3 classes contain R", ifelse(!isTRUE(combine_SI), " or I", ""), ": ", x$classes_affected[which(x$classes_affected >= 3)], " out of ", x$classes_available[which(x$classes_affected >= 3)], " available classes" ) } # XDR (=3): all but <=2 classes affected x[which((x$classes_in_guideline - x$classes_affected) <= 2), "MDRO"] <- 3 if (isTRUE(verbose)) { x[which(x$MDRO == 3), "reason"] <- paste0( "less than 3 classes remain susceptible (", x$classes_in_guideline[which((x$classes_in_guideline - x$classes_affected) <= 2)] - x$classes_affected[which(x$MDRO == 3)], " out of ", x$classes_in_guideline[which(x$MDRO == 3)], " classes)" ) } # PDR (=4): all drugs are R x[which(x$classes_affected == 999 & x$classes_in_guideline == x$classes_available), "MDRO"] <- 4 if (isTRUE(verbose)) { x[which(x$MDRO == 4), "reason"] <- paste( "all antibiotics in all", x$classes_in_guideline[which(x$MDRO == 4)], "classes were tested R", ifelse(!isTRUE(combine_SI), " or I", "") ) } # not enough classes available x[which(x$MDRO %in% c(1, 3) & x$classes_available < floor(x$classes_in_guideline * pct_required_classes)), "MDRO"] <- -1 if (isTRUE(verbose)) { x[which(x$MDRO == -1), "reason"] <- paste0( "not enough classes available: ", x$classes_available[which(x$MDRO == -1)], " of required ", (floor(x$classes_in_guideline * pct_required_classes))[which(x$MDRO == -1)], " (~", percentage(pct_required_classes), " of ", x$classes_in_guideline[which(x$MDRO == -1)], ")" ) } # add antibiotic names of resistant ones to verbose output } if (guideline$code == "eucast3.1") { # EUCAST 3.1 -------------------------------------------------------------- # Table 5 trans_tbl( 3, which(x$order == "Enterobacterales" | (x$genus == "Pseudomonas" & x$species == "aeruginosa") | x$genus == "Acinetobacter"), COL, "all" ) trans_tbl( 3, which(x$genus == "Salmonella" & x$species == "Typhi"), c(carbapenems, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Haemophilus" & x$species == "influenzae"), c(cephalosporins_3rd, carbapenems, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Moraxella" & x$species == "catarrhalis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "meningitidis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "gonorrhoeae"), AZM, "any" ) # Table 6 trans_tbl( 3, which(x$fullname %like% "^(Coagulase-negative|Staphylococcus (aureus|epidermidis|hominis|haemolyticus|intermedius|pseudointermedius))"), c(VAN, TEC, DAP, LNZ, QDA, TGC), "any" ) trans_tbl( 3, which(x$genus == "Corynebacterium"), c(VAN, TEC, DAP, LNZ, QDA, TGC), "any" ) trans_tbl( 3, which(x$genus == "Streptococcus" & x$species == "pneumoniae"), c(carbapenems, VAN, TEC, DAP, LNZ, QDA, TGC, RIF), "any" ) trans_tbl( 3, # Sr. groups A/B/C/G which(x$fullname %like% "^Streptococcus (group (A|B|C|G)|pyogenes|agalactiae|equisimilis|equi|zooepidemicus|dysgalactiae|anginosus)"), c(PEN, cephalosporins, VAN, TEC, DAP, LNZ, QDA, TGC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus"), c(DAP, LNZ, TGC, TEC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus" & x$species == "faecalis"), c(AMP, AMX), "any" ) # Table 7 trans_tbl( 3, which(x$genus == "Bacteroides"), MTR, "any" ) trans_tbl( 3, which(x$genus %in% c("Clostridium", "Clostridioides") & x$species == "difficile"), c(MTR, VAN), "any" ) } if (guideline$code == "eucast3.2") { # EUCAST 3.2 -------------------------------------------------------------- # Table 6 trans_tbl( 3, which((x$order == "Enterobacterales" & !x$family == "Morganellaceae" & !(x$genus == "Serratia" & x$species == "marcescens")) | (x$genus == "Pseudomonas" & x$species == "aeruginosa") | x$genus == "Acinetobacter"), COL, "all" ) trans_tbl( 3, which(x$genus == "Salmonella" & x$species == "Typhi"), c(carbapenems), "any" ) trans_tbl( 3, which(x$genus == "Haemophilus" & x$species == "influenzae"), c(cephalosporins_3rd, carbapenems, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Moraxella" & x$species == "catarrhalis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "meningitidis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "gonorrhoeae"), SPT, "any" ) # Table 7 trans_tbl( 3, which(x$genus == "Staphylococcus" & x$species == "aureus"), c(VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$mo %in% MO_CONS), # coagulase-negative Staphylococcus c(VAN, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$genus == "Corynebacterium"), c(VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC), "any" ) trans_tbl( 3, which(x$genus == "Streptococcus" & x$species == "pneumoniae"), c(carbapenems, VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC, RIF), "any" ) trans_tbl( 3, # Sr. groups A/B/C/G which(x$mo %in% MO_STREP_ABCG), c(PEN, cephalosporins, VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus"), c(DAP, LNZ, TGC, ERV, OMC, TEC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus" & x$species == "faecalis"), c(AMP, AMX), "any" ) # Table 8 trans_tbl( 3, which(x$genus == "Bacteroides"), MTR, "any" ) trans_tbl( 3, which(x$genus %in% c("Clostridium", "Clostridioides") & x$species == "difficile"), c(MTR, VAN, FDX), "any" ) } if (guideline$code == "eucast3.3") { # EUCAST 3.3 -------------------------------------------------------------- # note: this guideline is equal to EUCAST 3.2 - no MDRO insights changed # Table 6 trans_tbl( 3, which((x$order == "Enterobacterales" & !x$family == "Morganellaceae" & !(x$genus == "Serratia" & x$species == "marcescens")) | (x$genus == "Pseudomonas" & x$species == "aeruginosa") | x$genus == "Acinetobacter"), COL, "all" ) trans_tbl( 3, which(x$genus == "Salmonella" & x$species == "Typhi"), c(carbapenems), "any" ) trans_tbl( 3, which(x$genus == "Haemophilus" & x$species == "influenzae"), c(cephalosporins_3rd, carbapenems, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Moraxella" & x$species == "catarrhalis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "meningitidis"), c(cephalosporins_3rd, fluoroquinolones), "any" ) trans_tbl( 3, which(x$genus == "Neisseria" & x$species == "gonorrhoeae"), SPT, "any" ) # Table 7 trans_tbl( 3, which(x$genus == "Staphylococcus" & x$species == "aureus"), c(VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$mo %in% MO_CONS), # coagulase-negative Staphylococcus c(VAN, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$genus == "Corynebacterium"), c(VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC), "any" ) trans_tbl( 3, which(x$genus == "Streptococcus" & x$species == "pneumoniae"), c(carbapenems, VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC, RIF), "any" ) trans_tbl( 3, # Sr. groups A/B/C/G which(x$mo %in% MO_STREP_ABCG), c(PEN, cephalosporins, VAN, TEC, TLV, DAL, ORI, DAP, LNZ, TZD, QDA, TGC, ERV, OMC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus"), c(DAP, LNZ, TGC, ERV, OMC, TEC), "any" ) trans_tbl( 3, which(x$genus == "Enterococcus" & x$species == "faecalis"), c(AMP, AMX), "any" ) # Table 8 trans_tbl( 3, which(x$genus == "Bacteroides"), MTR, "any" ) trans_tbl( 3, which(x$genus %in% c("Clostridium", "Clostridioides") & x$species == "difficile"), c(MTR, VAN, FDX), "any" ) } if (guideline$code == "mrgn") { # Germany ----------------------------------------------------------------- # Table 1 trans_tbl( 2, # 3MRGN which((x$order == "Enterobacterales" | # following in fact the old Enterobacteriaceae classification (x$genus == "Acinetobacter" & x$species == "baumannii")) & try_ab(x[, PIP, drop = TRUE] == "R") & (try_ab(x[, CTX, drop = TRUE] == "R") | try_ab(x[, CAZ, drop = TRUE] == "R")) & (try_ab(x[, IPM, drop = TRUE] != "R") | try_ab(x[, MEM, drop = TRUE] != "R")) & try_ab(x[, CIP, drop = TRUE] == "R")), c(PIP, CTX, CAZ, IPM, MEM, CIP), "any" ) trans_tbl( 3, # 4MRGN, overwrites 3MRGN if applicable which((x$order == "Enterobacterales" | # following in fact the old Enterobacteriaceae classification (x$genus == "Acinetobacter" & x$species == "baumannii")) & try_ab(x[, PIP, drop = TRUE] == "R") & (try_ab(x[, CTX, drop = TRUE] == "R") | try_ab(x[, CAZ, drop = TRUE] == "R")) & (try_ab(x[, IPM, drop = TRUE] == "R") | try_ab(x[, MEM, drop = TRUE] == "R")) & try_ab(x[, CIP, drop = TRUE] == "R")), c(PIP, CTX, CAZ, IPM, MEM, CIP), "any" ) trans_tbl( 3, # 4MRGN, overwrites 3MRGN if applicable which((x$order == "Enterobacterales" | # following in fact the old Enterobacteriaceae classification (x$genus == "Acinetobacter" & x$species == "baumannii")) & (try_ab(x[, IPM, drop = TRUE] == "R") | try_ab(x[, MEM, drop = TRUE] == "R"))), c(IPM, MEM), "any" ) trans_tbl( 2, # 3MRGN, if only 1 group is S which(x$genus == "Pseudomonas" & x$species == "aeruginosa" & try_ab(x[, PIP, drop = TRUE] == "S") + try_ab(x[, CTX, drop = TRUE] == "S") + try_ab(x[, CAZ, drop = TRUE] == "S") + try_ab(x[, IPM, drop = TRUE] == "S") + try_ab(x[, MEM, drop = TRUE] == "S") + try_ab(x[, CIP, drop = TRUE] == "S") == 1), c(PIP, CTX, CAZ, IPM, MEM, CIP), "any" ) trans_tbl( 3, # 4MRGN otherwise which((x$genus == "Pseudomonas" & x$species == "aeruginosa") & try_ab(x[, PIP, drop = TRUE] == "R") & (try_ab(x[, CTX, drop = TRUE] == "R") | try_ab(x[, CAZ, drop = TRUE] == "R")) & (try_ab(x[, IPM, drop = TRUE] == "R") | try_ab(x[, MEM, drop = TRUE] == "R")) & try_ab(x[, CIP, drop = TRUE] == "R")), c(PIP, CTX, CAZ, IPM, MEM, CIP), "any" ) x[which(x$MDRO == 2), "reason"] <- "3MRGN" x[which(x$MDRO == 3), "reason"] <- "4MRGN" } if (guideline$code == "brmo") { # Netherlands ------------------------------------------------------------- aminoglycosides <- aminoglycosides[!is.na(aminoglycosides)] fluoroquinolones <- fluoroquinolones[!is.na(fluoroquinolones)] carbapenems <- carbapenems[!is.na(carbapenems)] amino <- AMX %or% AMP third <- CAZ %or% CTX ESBLs <- c(amino, third) ESBLs <- ESBLs[!is.na(ESBLs)] if (length(ESBLs) != 2) { ESBLs <- character(0) } # Table 1 trans_tbl( 3, which(x$order == "Enterobacterales"), # following in fact the old Enterobacteriaceae classification c(aminoglycosides, fluoroquinolones), "all" ) trans_tbl( 2, which(x$order == "Enterobacterales"), # following in fact the old Enterobacteriaceae classification carbapenems, "any" ) trans_tbl( 2, which(x$order == "Enterobacterales"), # following in fact the old Enterobacteriaceae classification ESBLs, "all" ) # Table 2 trans_tbl( 2, which(x$genus == "Acinetobacter"), c(carbapenems), "any" ) trans_tbl( 3, which(x$genus == "Acinetobacter"), c(aminoglycosides, fluoroquinolones), "all" ) trans_tbl( 3, which(x$genus == "Stenotrophomonas" & x$species == "maltophilia"), SXT, "all" ) if (!ab_missing(MEM) && !ab_missing(IPM) && !ab_missing(GEN) && !ab_missing(TOB) && !ab_missing(CIP) && !ab_missing(CAZ) && !ab_missing(TZP)) { x$psae <- 0 x[which(x[, MEM, drop = TRUE] == "R" | x[, IPM, drop = TRUE] == "R"), "psae"] <- 1 + x[which(x[, MEM, drop = TRUE] == "R" | x[, IPM, drop = TRUE] == "R"), "psae"] x[which(x[, GEN, drop = TRUE] == "R" & x[, TOB, drop = TRUE] == "R"), "psae"] <- 1 + x[which(x[, GEN, drop = TRUE] == "R" & x[, TOB, drop = TRUE] == "R"), "psae"] x[which(x[, CIP, drop = TRUE] == "R"), "psae"] <- 1 + x[which(x[, CIP, drop = TRUE] == "R"), "psae"] x[which(x[, CAZ, drop = TRUE] == "R"), "psae"] <- 1 + x[which(x[, CAZ, drop = TRUE] == "R"), "psae"] x[which(x[, TZP, drop = TRUE] == "R"), "psae"] <- 1 + x[which(x[, TZP, drop = TRUE] == "R"), "psae"] } else { x$psae <- 0 } trans_tbl( 3, which(x$genus == "Pseudomonas" & x$species == "aeruginosa" & x$psae >= 3), c(CAZ, CIP, GEN, IPM, MEM, TOB, TZP), "any" ) x[which( x$genus == "Pseudomonas" & x$species == "aeruginosa" & x$psae >= 3 ), "reason"] <- paste0("at least 3 classes contain R", ifelse(!isTRUE(combine_SI), " or I", "")) # Table 3 trans_tbl( 3, which(x$genus == "Streptococcus" & x$species == "pneumoniae"), PEN, "all" ) trans_tbl( 3, which(x$genus == "Streptococcus" & x$species == "pneumoniae"), VAN, "all" ) trans_tbl( 3, which(x$genus == "Enterococcus" & x$species == "faecium"), c(PEN, VAN), "all" ) } if (guideline$code == "tb") { # Tuberculosis ------------------------------------------------------------ prepare_drug <- function(ab) { # returns vector values of drug # if `ab` is a column name, looks up the values in `x` if (length(ab) == 1 && is.character(ab)) { if (ab %in% colnames(x)) { ab <- x[, ab, drop = TRUE] } } ab <- as.character(as.sir(ab)) ab[is.na(ab)] <- "" ab } drug_is_R <- function(ab) { # returns [logical] vector ab <- prepare_drug(ab) if (length(ab) == 0) { rep(FALSE, NROW(x)) } else if (length(ab) == 1) { rep(ab, NROW(x)) == "R" } else { ab == "R" } } drug_is_not_R <- function(ab) { # returns [logical] vector ab <- prepare_drug(ab) if (length(ab) == 0) { rep(TRUE, NROW(x)) } else if (length(ab) == 1) { rep(ab, NROW(x)) != "R" } else { ab != "R" } } x$mono_count <- 0 x[drug_is_R(INH), "mono_count"] <- x[drug_is_R(INH), "mono_count", drop = TRUE] + 1 x[drug_is_R(RIF), "mono_count"] <- x[drug_is_R(RIF), "mono_count", drop = TRUE] + 1 x[drug_is_R(ETH), "mono_count"] <- x[drug_is_R(ETH), "mono_count", drop = TRUE] + 1 x[drug_is_R(PZA), "mono_count"] <- x[drug_is_R(PZA), "mono_count", drop = TRUE] + 1 x[drug_is_R(RIB), "mono_count"] <- x[drug_is_R(RIB), "mono_count", drop = TRUE] + 1 x[drug_is_R(RFP), "mono_count"] <- x[drug_is_R(RFP), "mono_count", drop = TRUE] + 1 x$mono <- x$mono_count > 0 x$poly <- x$mono_count > 1 & drug_is_not_R(RIF) & drug_is_not_R(INH) x$mdr <- drug_is_R(RIF) & drug_is_R(INH) x$xdr <- drug_is_R(LVX) | drug_is_R(MFX) | drug_is_R(GAT) x$second <- drug_is_R(CAP) | drug_is_R(KAN) | drug_is_R(AMK) x$xdr <- x$mdr & x$xdr & x$second x$MDRO <- ifelse(x$xdr, 5, ifelse(x$mdr, 4, ifelse(x$poly, 3, ifelse(x$mono, 2, 1 ) ) ) ) # keep all real TB, make other species NA x$MDRO <- ifelse(x$fullname == "Mycobacterium tuberculosis", x$MDRO, NA_real_) x$reason <- "PDR/MDR/XDR criteria were met" } # some more info on negative results if (isTRUE(verbose)) { if (guideline$code == "cmi2012") { x[which(x$MDRO == 1 & !is.na(x$classes_affected)), "reason"] <- paste0( x$classes_affected[which(x$MDRO == 1 & !is.na(x$classes_affected))], " of ", x$classes_available[which(x$MDRO == 1 & !is.na(x$classes_affected))], " available classes contain R", ifelse(!isTRUE(combine_SI), " or I", ""), " (3 required for MDR)" ) } else { x[which(x$MDRO == 1), "reason"] <- "too few antibiotics are R" } } if (isTRUE(info.bak)) { cat(group_msg) if (sum(!is.na(x$MDRO)) == 0) { cat(font_bold(paste0("=> Found 0 MDROs since no isolates are covered by the guideline"))) } else { cat(font_bold(paste0( "=> Found ", sum(x$MDRO %in% 2:5, na.rm = TRUE), " ", guideline$type, " out of ", sum(!is.na(x$MDRO)), " isolates (", trimws(percentage(sum(x$MDRO %in% 2:5, na.rm = TRUE) / sum(!is.na(x$MDRO)))), ")" ))) } } # Fill in blanks ---- # for rows that have no results x_transposed <- as.list(as.data.frame(t(x[, cols_ab, drop = FALSE]), stringsAsFactors = FALSE )) rows_empty <- which(vapply( FUN.VALUE = logical(1), x_transposed, function(y) all(is.na(y)) )) if (length(rows_empty) > 0) { if (isTRUE(info.bak)) { cat(font_italic(paste0(" (", length(rows_empty), " isolates had no test results)\n"))) } x[rows_empty, "MDRO"] <- NA x[rows_empty, "reason"] <- "none of the antibiotics have test results" } else if (isTRUE(info.bak)) { cat("\n") } # Results ---- if (guideline$code == "cmi2012") { if (any(x$MDRO == -1, na.rm = TRUE)) { if (message_not_thrown_before("mdro", "availability")) { warning_( "in `mdro()`: NA introduced for isolates where the available percentage of antimicrobial classes was below ", percentage(pct_required_classes), " (set with `pct_required_classes`)" ) } # set these -1s to NA x[which(x$MDRO == -1), "MDRO"] <- NA_integer_ } x$MDRO <- factor( x = x$MDRO, levels = 1:4, labels = c( "Negative", "Multi-drug-resistant (MDR)", "Extensively drug-resistant (XDR)", "Pandrug-resistant (PDR)" ), ordered = TRUE ) } else if (guideline$code == "tb") { x$MDRO <- factor( x = x$MDRO, levels = 1:5, labels = c( "Negative", "Mono-resistant", "Poly-resistant", "Multi-drug-resistant", "Extensively drug-resistant" ), ordered = TRUE ) } else if (guideline$code == "mrgn") { x$MDRO <- factor( x = x$MDRO, levels = 1:3, labels = c("Negative", "3MRGN", "4MRGN"), ordered = TRUE ) } else { x$MDRO <- factor( x = x$MDRO, levels = 1:3, labels = c("Negative", "Positive, unconfirmed", "Positive"), ordered = TRUE ) } if (isTRUE(verbose)) { colnames(x)[colnames(x) == col_mo] <- "microorganism" x$microorganism <- mo_name(x$microorganism, language = NULL) x[, c( "row_number", "microorganism", "MDRO", "reason", "columns_nonsusceptible" ), drop = FALSE ] } else { x$MDRO } } #' @rdname mdro #' @export custom_mdro_guideline <- function(..., as_factor = TRUE) { meet_criteria(as_factor, allow_class = "logical", has_length = 1) dots <- tryCatch(list(...), error = function(e) "error" ) stop_if( identical(dots, "error"), "rules must be a valid formula inputs (e.g., using '~'), see `?mdro`" ) n_dots <- length(dots) stop_if(n_dots == 0, "no custom rules were set. Please read the documentation using `?mdro`.") out <- vector("list", n_dots) for (i in seq_len(n_dots)) { stop_ifnot( inherits(dots[[i]], "formula"), "rule ", i, " must be a valid formula input (e.g., using '~'), see `?mdro`" ) # Query qry <- dots[[i]][[2]] if (inherits(qry, "call")) { qry <- as.expression(qry) } qry <- as.character(qry) # these will prevent vectorisation, so replace them: qry <- gsub("&&", "&", qry, fixed = TRUE) qry <- gsub("||", "|", qry, fixed = TRUE) # support filter()-like writing: custom_mdro_guideline('CIP == "R", AMX == "S"' ~ "result 1") qry <- gsub(" *, *", " & ", qry) # format nicely, setting spaces around operators qry <- gsub(" *([&|+-/*^><==]+) *", " \\1 ", qry) qry <- gsub("'", "\"", qry, fixed = TRUE) out[[i]]$query <- as.expression(qry) # Value val <- tryCatch(eval(dots[[i]][[3]]), error = function(e) NULL) stop_if(is.null(val), "rule ", i, " must return a valid value, it now returns an error: ", tryCatch(eval(dots[[i]][[3]]), error = function(e) e$message)) stop_if(length(val) > 1, "rule ", i, " must return a value of length 1, not ", length(val)) out[[i]]$value <- as.character(val) } names(out) <- paste0("rule", seq_len(n_dots)) out <- set_clean_class(out, new_class = c("custom_mdro_guideline", "list")) attr(out, "values") <- unname(c("Negative", vapply(FUN.VALUE = character(1), unclass(out), function(x) x$value))) attr(out, "as_factor") <- as_factor out } #' @method c custom_mdro_guideline #' @noRd #' @export c.custom_mdro_guideline <- function(x, ..., as_factor = NULL) { if (length(list(...)) == 0) { return(x) } if (!is.null(as_factor)) { meet_criteria(as_factor, allow_class = "logical", has_length = 1) } else { as_factor <- attributes(x)$as_factor } for (g in list(...)) { stop_ifnot(inherits(g, "custom_mdro_guideline"), "for combining custom MDRO guidelines, all rules must be created with `custom_mdro_guideline()`", call = FALSE ) vals <- attributes(x)$values if (!all(attributes(g)$values %in% vals)) { vals <- unname(unique(c(vals, attributes(g)$values))) } attributes(g) <- NULL x <- c(unclass(x), unclass(g)) attr(x, "values") <- vals } names(x) <- paste0("rule", seq_len(length(x))) x <- set_clean_class(x, new_class = c("custom_mdro_guideline", "list")) attr(x, "values") <- vals attr(x, "as_factor") <- as_factor x } #' @method as.list custom_mdro_guideline #' @noRd #' @export as.list.custom_mdro_guideline <- function(x, ...) { c(x, ...) } #' @method print custom_mdro_guideline #' @export #' @noRd print.custom_mdro_guideline <- function(x, ...) { cat("A set of custom MDRO rules:\n") for (i in seq_len(length(x))) { rule <- x[[i]] rule$query <- format_custom_query_rule(rule$query) cat(" ", i, ". ", font_bold("If "), font_blue(rule$query), font_bold(" then: "), font_red(rule$value), "\n", sep = "") } cat(" ", i + 1, ". ", font_bold("Otherwise: "), font_red(paste0("Negative")), "\n", sep = "") cat("\nUnmatched rows will return ", font_red("NA"), ".\n", sep = "") if (isTRUE(attributes(x)$as_factor)) { cat("Results will be of class 'factor', with ordered levels: ", paste0(attributes(x)$values, collapse = " < "), "\n", sep = "") } else { cat("Results will be of class 'character'.\n") } } run_custom_mdro_guideline <- function(df, guideline, info) { n_dots <- length(guideline) stop_if(n_dots == 0, "no custom guidelines set", call = -2) out <- character(length = NROW(df)) reasons <- character(length = NROW(df)) for (i in seq_len(n_dots)) { qry <- tryCatch(eval(parse(text = guideline[[i]]$query), envir = df, enclos = parent.frame()), error = function(e) { AMR_env$err_msg <- e$message return("error") } ) if (identical(qry, "error")) { warning_("in `custom_mdro_guideline()`: rule ", i, " (`", as.character(guideline[[i]]$query), "`) was ignored because of this error message: ", AMR_env$err_msg, call = FALSE, add_fn = font_red ) next } stop_ifnot(is.logical(qry), "in custom_mdro_guideline(): rule ", i, " (`", guideline[[i]]$query, "`) must return `TRUE` or `FALSE`, not ", format_class(class(qry), plural = FALSE), call = FALSE ) new_mdros <- which(qry == TRUE & out == "") if (isTRUE(info)) { cat(word_wrap( "- Custom MDRO rule ", i, ": `", as.character(guideline[[i]]$query), "` (", length(new_mdros), " rows matched)" ), "\n", sep = "") } val <- guideline[[i]]$value out[new_mdros] <- val reasons[new_mdros] <- paste0( "matched rule ", gsub("rule", "", names(guideline)[i], fixed = TRUE), ": ", as.character(guideline[[i]]$query) ) } out[out == ""] <- "Negative" reasons[out == "Negative"] <- "no rules matched" if (isTRUE(attributes(guideline)$as_factor)) { out <- factor(out, levels = attributes(guideline)$values, ordered = TRUE) } columns_nonsusceptible <- as.data.frame(t(df[, is.sir(df), drop = FALSE] == "R")) columns_nonsusceptible <- vapply( FUN.VALUE = character(1), columns_nonsusceptible, function(x) paste0(rownames(columns_nonsusceptible)[which(x)], collapse = " ") ) columns_nonsusceptible[is.na(out)] <- NA_character_ data.frame( row_number = seq_len(NROW(df)), MDRO = out, reason = reasons, columns_nonsusceptible = columns_nonsusceptible, stringsAsFactors = FALSE ) } #' @rdname mdro #' @export brmo <- function(x = NULL, only_sir_columns = FALSE, ...) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) stop_if( "guideline" %in% names(list(...)), "argument `guideline` must not be set since this is a guideline-specific function" ) mdro(x = x, only_sir_columns = only_sir_columns, guideline = "BRMO", ...) } #' @rdname mdro #' @export mrgn <- function(x = NULL, only_sir_columns = FALSE, ...) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) stop_if( "guideline" %in% names(list(...)), "argument `guideline` must not be set since this is a guideline-specific function" ) mdro(x = x, only_sir_columns = only_sir_columns, guideline = "MRGN", ...) } #' @rdname mdro #' @export mdr_tb <- function(x = NULL, only_sir_columns = FALSE, ...) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) stop_if( "guideline" %in% names(list(...)), "argument `guideline` must not be set since this is a guideline-specific function" ) mdro(x = x, only_sir_columns = only_sir_columns, guideline = "TB", ...) } #' @rdname mdro #' @export mdr_cmi2012 <- function(x = NULL, only_sir_columns = FALSE, ...) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) stop_if( "guideline" %in% names(list(...)), "argument `guideline` must not be set since this is a guideline-specific function" ) mdro(x = x, only_sir_columns = only_sir_columns, guideline = "CMI2012", ...) } #' @rdname mdro #' @export eucast_exceptional_phenotypes <- function(x = NULL, only_sir_columns = FALSE, ...) { meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1) stop_if( "guideline" %in% names(list(...)), "argument `guideline` must not be set since this is a guideline-specific function" ) mdro(x = x, only_sir_columns = only_sir_columns, guideline = "EUCAST", ...) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mdro.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Calculate the Mean AMR Distance #' #' Calculates a normalised mean for antimicrobial resistance between multiple observations, to help to identify similar isolates without comparing antibiograms by hand. #' @param x a vector of class [sir][as.sir()], [mic][as.mic()] or [disk][as.disk()], or a [data.frame] containing columns of any of these classes #' @param ... variables to select (supports [tidyselect language][tidyselect::language] such as `column1:column4` and `where(is.mic)`, and can thus also be [antibiotic selectors][ab_selector()] #' @param combine_SI a [logical] to indicate whether all values of S and I must be merged into one, so the input only consists of S+I vs. R (susceptible vs. resistant) - the default is `TRUE` #' @details The mean AMR distance is effectively [the Z-score](https://en.wikipedia.org/wiki/Standard_score); a normalised numeric value to compare AMR test results which can help to identify similar isolates, without comparing antibiograms by hand. #' #' MIC values (see [as.mic()]) are transformed with [log2()] first; their distance is thus calculated as `(log2(x) - mean(log2(x))) / sd(log2(x))`. #' #' SIR values (see [as.sir()]) are transformed using `"S"` = 1, `"I"` = 2, and `"R"` = 3. If `combine_SI` is `TRUE` (default), the `"I"` will be considered to be 1. #' #' For data sets, the mean AMR distance will be calculated per column, after which the mean per row will be returned, see *Examples*. #' #' Use [amr_distance_from_row()] to subtract distances from the distance of one row, see *Examples*. #' @section Interpretation: #' Isolates with distances less than 0.01 difference from each other should be considered similar. Differences lower than 0.025 should be considered suspicious. #' @export #' @examples #' sir <- random_sir(10) #' sir #' mean_amr_distance(sir) #' #' mic <- random_mic(10) #' mic #' mean_amr_distance(mic) #' # equal to the Z-score of their log2: #' (log2(mic) - mean(log2(mic))) / sd(log2(mic)) #' #' disk <- random_disk(10) #' disk #' mean_amr_distance(disk) #' #' y <- data.frame( #' id = LETTERS[1:10], #' amox = random_sir(10, ab = "amox", mo = "Escherichia coli"), #' cipr = random_disk(10, ab = "cipr", mo = "Escherichia coli"), #' gent = random_mic(10, ab = "gent", mo = "Escherichia coli"), #' tobr = random_mic(10, ab = "tobr", mo = "Escherichia coli") #' ) #' y #' mean_amr_distance(y) #' y$amr_distance <- mean_amr_distance(y, where(is.mic)) #' y[order(y$amr_distance), ] #' #' if (require("dplyr")) { #' y %>% #' mutate( #' amr_distance = mean_amr_distance(y), #' check_id_C = amr_distance_from_row(amr_distance, id == "C") #' ) %>% #' arrange(check_id_C) #' } #' if (require("dplyr")) { #' # support for groups #' example_isolates %>% #' filter(mo_genus() == "Enterococcus" & mo_species() != "") %>% #' select(mo, TCY, carbapenems()) %>% #' group_by(mo) %>% #' mutate(dist = mean_amr_distance(.)) %>% #' arrange(mo, dist) #' } mean_amr_distance <- function(x, ...) { UseMethod("mean_amr_distance") } #' @noRd #' @export mean_amr_distance.default <- function(x, ...) { x <- as.double(x) # calculate z-score (x - mean(x, na.rm = TRUE)) / stats::sd(x, na.rm = TRUE) } #' @noRd #' @export mean_amr_distance.mic <- function(x, ...) { mean_amr_distance(log2(x)) } #' @noRd #' @export mean_amr_distance.disk <- function(x, ...) { mean_amr_distance(as.double(x)) } #' @rdname mean_amr_distance #' @export mean_amr_distance.sir <- function(x, ..., combine_SI = TRUE) { meet_criteria(combine_SI, allow_class = "logical", has_length = 1, .call_depth = -1) if (isTRUE(combine_SI)) { x[x == "I"] <- "S" } mean_amr_distance(as.double(x)) } #' @rdname mean_amr_distance #' @export mean_amr_distance.data.frame <- function(x, ..., combine_SI = TRUE) { meet_criteria(combine_SI, allow_class = "logical", has_length = 1, .call_depth = -1) df <- x if (is_null_or_grouped_tbl(df)) { df <- get_current_data("x", -2) } df <- as.data.frame(df, stringsAsFactors = FALSE) if (tryCatch(length(list(...)) > 0, error = function(e) TRUE)) { out <- tryCatch(suppressWarnings(c(...)), error = function(e) NULL) if (!is.null(out)) { df <- df[, out, drop = FALSE] } else { df <- pm_select(df, ...) } } df_classes <- colnames(df)[vapply(FUN.VALUE = logical(1), df, function(x) is.disk(x) | is.mic(x) | is.disk(x), USE.NAMES = FALSE)] df_antibiotics <- unname(get_column_abx(df, info = FALSE)) df <- df[, colnames(df)[colnames(df) %in% union(df_classes, df_antibiotics)], drop = FALSE] stop_if(ncol(df) < 2, "data set must contain at least two variables", call = -2 ) if (message_not_thrown_before("mean_amr_distance", "groups")) { message_("Calculating mean AMR distance based on columns ", vector_and(colnames(df), sort = FALSE)) } res <- vapply( FUN.VALUE = double(nrow(df)), df, mean_amr_distance, combine_SI = combine_SI ) if (is.null(dim(res))) { if (all(is.na(res))) { return(NA_real_) } else { return(mean(res, na.rm = TRUE)) } } res <- rowMeans(res, na.rm = TRUE) res[is.infinite(res) | is.nan(res)] <- 0 res } #' @rdname mean_amr_distance #' @param amr_distance the outcome of [mean_amr_distance()] #' @param row an index, such as a row number #' @export amr_distance_from_row <- function(amr_distance, row) { meet_criteria(amr_distance, allow_class = c("double", "numeric"), is_finite = TRUE) meet_criteria(row, allow_class = c("logical", "double", "numeric")) if (is.logical(row)) { row <- which(row) } abs(amr_distance[row] - amr_distance) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mean_amr_distance.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # # these are allowed MIC values and will become [factor] levels operators <- c("<", "<=", "", ">=", ">") valid_mic_levels <- c( c(t(vapply( FUN.VALUE = character(6), operators, function(x) paste0(x, "0.000", c(1:4, 6, 8)) ))), c(t(vapply( FUN.VALUE = character(90), operators, function(x) paste0(x, "0.00", c(1:9, 11:19, 21:29, 31:39, 41:49, 51:59, 61:69, 71:79, 81:89, 91:99)) ))), unique(c(t(vapply( FUN.VALUE = character(106), operators, function(x) { paste0(x, sort(as.double(paste0( "0.0", sort(c(1:99, 125, 128, 156, 165, 256, 512, 625)) )))) } )))), unique(c(t(vapply( FUN.VALUE = character(103), operators, function(x) { paste0(x, sort(as.double(paste0( "0.", c(1:99, 125, 128, 256, 512) )))) } )))), c(t(vapply( FUN.VALUE = character(10), operators, function(x) paste0(x, sort(c(1:9, 1.5))) ))), c(t(vapply( FUN.VALUE = character(45), operators, function(x) paste0(x, c(10:98)[9:98 %% 2 == TRUE]) ))), c(t(vapply( FUN.VALUE = character(17), operators, function(x) paste0(x, sort(c(2^c(7:11), 192, 80 * c(2:12)))) ))) ) #' Transform Input to Minimum Inhibitory Concentrations (MIC) #' #' This transforms vectors to a new class [`mic`], which treats the input as decimal numbers, while maintaining operators (such as ">=") and only allowing valid MIC values known to the field of (medical) microbiology. #' @rdname as.mic #' @param x a [character] or [numeric] vector #' @param na.rm a [logical] indicating whether missing values should be removed #' @param ... arguments passed on to methods #' @details To interpret MIC values as SIR values, use [as.sir()] on MIC values. It supports guidelines from EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "CLSI")$guideline)))`). #' #' This class for MIC values is a quite a special data type: formally it is an ordered [factor] with valid MIC values as [factor] levels (to make sure only valid MIC values are retained), but for any mathematical operation it acts as decimal numbers: #' #' ``` #' x <- random_mic(10) #' x #' #> Class 'mic' #' #> [1] 16 1 8 8 64 >=128 0.0625 32 32 16 #' #' is.factor(x) #' #> [1] TRUE #' #' x[1] * 2 #' #> [1] 32 #' #' median(x) #' #> [1] 26 #' ``` #' #' This makes it possible to maintain operators that often come with MIC values, such ">=" and "<=", even when filtering using [numeric] values in data analysis, e.g.: #' #' ``` #' x[x > 4] #' #> Class 'mic' #' #> [1] 16 8 8 64 >=128 32 32 16 #' #' df <- data.frame(x, hospital = "A") #' subset(df, x > 4) # or with dplyr: df %>% filter(x > 4) #' #> x hospital #' #> 1 16 A #' #> 5 64 A #' #> 6 >=128 A #' #> 8 32 A #' #> 9 32 A #' #> 10 16 A #' ``` #' #' The following [generic functions][groupGeneric()] are implemented for the MIC class: `!`, `!=`, `%%`, `%/%`, `&`, `*`, `+`, `-`, `/`, `<`, `<=`, `==`, `>`, `>=`, `^`, `|`, [abs()], [acos()], [acosh()], [all()], [any()], [asin()], [asinh()], [atan()], [atanh()], [ceiling()], [cos()], [cosh()], [cospi()], [cummax()], [cummin()], [cumprod()], [cumsum()], [digamma()], [exp()], [expm1()], [floor()], [gamma()], [lgamma()], [log()], [log1p()], [log2()], [log10()], [max()], [mean()], [min()], [prod()], [range()], [round()], [sign()], [signif()], [sin()], [sinh()], [sinpi()], [sqrt()], [sum()], [tan()], [tanh()], [tanpi()], [trigamma()] and [trunc()]. Some functions of the `stats` package are also implemented: [median()], [quantile()], [mad()], [IQR()], [fivenum()]. Also, [boxplot.stats()] is supported. Since [sd()] and [var()] are non-generic functions, these could not be extended. Use [mad()] as an alternative, or use e.g. `sd(as.numeric(x))` where `x` is your vector of MIC values. #' #' Using [as.double()] or [as.numeric()] on MIC values will remove the operators and return a numeric vector. Do **not** use [as.integer()] on MIC values as by the \R convention on [factor]s, it will return the index of the factor levels (which is often useless for regular users). #' #' Use [droplevels()] to drop unused levels. At default, it will return a plain factor. Use `droplevels(..., as.mic = TRUE)` to maintain the `mic` class. #' @return Ordered [factor] with additional class [`mic`], that in mathematical operations acts as decimal numbers. Bare in mind that the outcome of any mathematical operation on MICs will return a [numeric] value. #' @aliases mic #' @export #' @seealso [as.sir()] #' @examples #' mic_data <- as.mic(c(">=32", "1.0", "1", "1.00", 8, "<=0.128", "8", "16", "16")) #' mic_data #' is.mic(mic_data) #' #' # this can also coerce combined MIC/SIR values: #' as.mic("<=0.002; S") #' #' # mathematical processing treats MICs as numeric values #' fivenum(mic_data) #' quantile(mic_data) #' all(mic_data < 512) #' #' # interpret MIC values #' as.sir( #' x = as.mic(2), #' mo = as.mo("Streptococcus pneumoniae"), #' ab = "AMX", #' guideline = "EUCAST" #' ) #' as.sir( #' x = as.mic(c(0.01, 2, 4, 8)), #' mo = as.mo("Streptococcus pneumoniae"), #' ab = "AMX", #' guideline = "EUCAST" #' ) #' #' # plot MIC values, see ?plot #' plot(mic_data) #' plot(mic_data, mo = "E. coli", ab = "cipro") #' #' if (require("ggplot2")) { #' autoplot(mic_data, mo = "E. coli", ab = "cipro") #' } #' if (require("ggplot2")) { #' autoplot(mic_data, mo = "E. coli", ab = "cipro", language = "nl") # Dutch #' } as.mic <- function(x, na.rm = FALSE) { meet_criteria(x, allow_NA = TRUE) meet_criteria(na.rm, allow_class = "logical", has_length = 1) if (is.mic(x)) { x } else { if (is.numeric(x)) { x <- format(x, scientific = FALSE) } else { x <- as.character(unlist(x)) } if (isTRUE(na.rm)) { x <- x[!is.na(x)] } x[trimws2(x) == ""] <- NA x.bak <- x # comma to period x <- gsub(",", ".", x, fixed = TRUE) # transform scientific notation x[x %like% "[-]?[0-9]+([.][0-9]+)?e[-]?[0-9]+"] <- as.double(x[x %like% "[-]?[0-9]+([.][0-9]+)?e[-]?[0-9]+"]) # transform Unicode for >= and <= x <- gsub("\u2264", "<=", x, fixed = TRUE) x <- gsub("\u2265", ">=", x, fixed = TRUE) # remove other invalid characters x <- gsub("[^a-zA-Z0-9.><= ]+", "", x, perl = TRUE) # remove space between operator and number ("<= 0.002" -> "<=0.002") x <- gsub("(<|=|>) +", "\\1", x, perl = TRUE) # transform => to >= and =< to <= x <- gsub("=<", "<=", x, fixed = TRUE) x <- gsub("=>", ">=", x, fixed = TRUE) # dots without a leading zero must start with 0 x <- gsub("([^0-9]|^)[.]", "\\10.", x, perl = TRUE) # values like "<=0.2560.512" should be 0.512 x <- gsub(".*[.].*[.]", "0.", x, perl = TRUE) # remove ending .0 x <- gsub("[.]+0$", "", x, perl = TRUE) # remove all after last digit x <- gsub("[^0-9]+$", "", x, perl = TRUE) # keep only one zero before dot x <- gsub("0+[.]", "0.", x, perl = TRUE) # starting 00 is probably 0.0 if there's no dot yet x[x %unlike% "[.]"] <- gsub("^00", "0.0", x[!x %like% "[.]"]) # remove last zeroes x <- gsub("([.].?)0+$", "\\1", x, perl = TRUE) x <- gsub("(.*[.])0+$", "\\10", x, perl = TRUE) # remove ending .0 again x[x %like% "[.]"] <- gsub("0+$", "", x[x %like% "[.]"]) # never end with dot x <- gsub("[.]$", "", x, perl = TRUE) # trim it x <- trimws2(x) ## previously unempty values now empty - should return a warning later on x[x.bak != "" & x == ""] <- "invalid" na_before <- x[is.na(x) | x == ""] %pm>% length() x[!x %in% valid_mic_levels] <- NA na_after <- x[is.na(x) | x == ""] %pm>% length() if (na_before != na_after) { list_missing <- x.bak[is.na(x) & !is.na(x.bak) & x.bak != ""] %pm>% unique() %pm>% sort() %pm>% vector_and(quotes = TRUE) cur_col <- get_current_column() warning_("in `as.mic()`: ", na_after - na_before, " result", ifelse(na_after - na_before > 1, "s", ""), ifelse(is.null(cur_col), "", paste0(" in column '", cur_col, "'")), " truncated (", round(((na_after - na_before) / length(x)) * 100), "%) that were invalid MICs: ", list_missing, call = FALSE ) } set_clean_class(factor(x, levels = valid_mic_levels, ordered = TRUE), new_class = c("mic", "ordered", "factor") ) } } all_valid_mics <- function(x) { if (!inherits(x, c("mic", "character", "factor", "numeric", "integer"))) { return(FALSE) } x_mic <- tryCatch(suppressWarnings(as.mic(x[!is.na(x)])), error = function(e) NA ) !any(is.na(x_mic)) && !all(is.na(x)) } #' @rdname as.mic #' @details `NA_mic_` is a missing value of the new `mic` class, analogous to e.g. base \R's [`NA_character_`][base::NA]. #' @format NULL #' @export NA_mic_ <- set_clean_class(factor(NA, levels = valid_mic_levels, ordered = TRUE), new_class = c("mic", "ordered", "factor") ) #' @rdname as.mic #' @export is.mic <- function(x) { inherits(x, "mic") } #' @method as.double mic #' @export #' @noRd as.double.mic <- function(x, ...) { as.double(gsub("[<=>]+", "", as.character(x), perl = TRUE)) } #' @method as.numeric mic #' @export #' @noRd as.numeric.mic <- function(x, ...) { as.numeric(gsub("[<=>]+", "", as.character(x), perl = TRUE)) } #' @rdname as.mic #' @method droplevels mic #' @param as.mic a [logical] to indicate whether the `mic` class should be kept - the default is `FALSE` #' @export droplevels.mic <- function(x, as.mic = FALSE, ...) { x <- droplevels.factor(x, ...) if (as.mic == TRUE) { class(x) <- c("mic", "ordered", "factor") } x } # will be exported using s3_register() in R/zzz.R pillar_shaft.mic <- function(x, ...) { crude_numbers <- as.double(x) operators <- gsub("[^<=>]+", "", as.character(x)) operators[!is.na(operators) & operators != ""] <- font_silver(operators[!is.na(operators) & operators != ""], collapse = NULL) out <- trimws(paste0(operators, trimws(format(crude_numbers)))) out[is.na(x)] <- font_na(NA) # maketrailing zeroes almost invisible out[out %like% "[.]"] <- gsub("([.]?0+)$", font_white("\\1"), out[out %like% "[.]"], perl = TRUE) create_pillar_column(out, align = "right", width = max(nchar(font_stripstyle(out)))) } # will be exported using s3_register() in R/zzz.R type_sum.mic <- function(x, ...) { "mic" } #' @method print mic #' @export #' @noRd print.mic <- function(x, ...) { cat("Class 'mic'", ifelse(length(levels(x)) < length(valid_mic_levels), font_red(" with dropped levels"), ""), "\n", sep = "" ) print(as.character(x), quote = FALSE) att <- attributes(x) if ("na.action" %in% names(att)) { cat(font_silver(paste0("(NA ", class(att$na.action), ": ", paste0(att$na.action, collapse = ", "), ")\n"))) } } #' @method summary mic #' @export #' @noRd summary.mic <- function(object, ...) { summary(as.double(object), ...) } #' @method as.matrix mic #' @export #' @noRd as.matrix.mic <- function(x, ...) { as.matrix(as.double(x), ...) } #' @method [ mic #' @export #' @noRd "[.mic" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [[ mic #' @export #' @noRd "[[.mic" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [<- mic #' @export #' @noRd "[<-.mic" <- function(i, j, ..., value) { value <- as.mic(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method [[<- mic #' @export #' @noRd "[[<-.mic" <- function(i, j, ..., value) { value <- as.mic(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method c mic #' @export #' @noRd c.mic <- function(...) { as.mic(unlist(lapply(list(...), as.character))) } #' @method unique mic #' @export #' @noRd unique.mic <- function(x, incomparables = FALSE, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method rep mic #' @export #' @noRd rep.mic <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method sort mic #' @export #' @noRd sort.mic <- function(x, decreasing = FALSE, ...) { if (decreasing == TRUE) { ord <- order(-as.double(x)) } else { ord <- order(as.double(x)) } x[ord] } #' @method hist mic #' @importFrom graphics hist #' @export #' @noRd hist.mic <- function(x, ...) { warning_("in `hist()`: use `plot()` or ggplot2's `autoplot()` for optimal plotting of MIC values") hist(log2(x)) } # will be exported using s3_register() in R/zzz.R get_skimmers.mic <- function(column) { skimr::sfl( skim_type = "mic", p0 = ~ stats::quantile(., probs = 0, na.rm = TRUE, names = FALSE), p25 = ~ stats::quantile(., probs = 0.25, na.rm = TRUE, names = FALSE), p50 = ~ stats::quantile(., probs = 0.5, na.rm = TRUE, names = FALSE), p75 = ~ stats::quantile(., probs = 0.75, na.rm = TRUE, names = FALSE), p100 = ~ stats::quantile(., probs = 1, na.rm = TRUE, names = FALSE), hist = ~ skimr::inline_hist(log2(stats::na.omit(.)), 5) ) } # Miscellaneous mathematical functions ------------------------------------ #' @method mean mic #' @export #' @noRd mean.mic <- function(x, trim = 0, na.rm = FALSE, ...) { mean(as.double(x), trim = trim, na.rm = na.rm, ...) } #' @method median mic #' @importFrom stats median #' @export #' @noRd median.mic <- function(x, na.rm = FALSE, ...) { median(as.double(x), na.rm = na.rm, ...) } #' @method quantile mic #' @importFrom stats quantile #' @export #' @noRd quantile.mic <- function(x, probs = seq(0, 1, 0.25), na.rm = FALSE, names = TRUE, type = 7, ...) { quantile(as.double(x), probs = probs, na.rm = na.rm, names = names, type = type, ...) } # Math (see ?groupGeneric) ------------------------------------------------ #' @export Math.mic <- function(x, ...) { x <- as.double(x) # set class to numeric, because otherwise NextMethod will be factor (since mic is a factor) .Class <- class(x) NextMethod(.Generic) } # Ops (see ?groupGeneric) ------------------------------------------------- #' @export Ops.mic <- function(e1, e2) { e1 <- as.double(e1) if (!missing(e2)) { # when e1 is `!`, e2 is missing e2 <- as.double(e2) } # set class to numeric, because otherwise NextMethod will be factor (since mic is a factor) .Class <- class(e1) NextMethod(.Generic) } # Complex (see ?groupGeneric) --------------------------------------------- #' @export Complex.mic <- function(z) { z <- as.double(z) # set class to numeric, because otherwise NextMethod will be factor (since mic is a factor) .Class <- class(z) NextMethod(.Generic) } # Summary (see ?groupGeneric) --------------------------------------------- #' @export Summary.mic <- function(..., na.rm = FALSE) { # NextMethod() cannot be called from an anonymous function (`...`), so we get() the generic directly: fn <- get(.Generic, envir = .GenericCallEnv) fn(as.double(c(...)), na.rm = na.rm) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mic.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Transform Arbitrary Input to Valid Microbial Taxonomy #' #' Use this function to get a valid microorganism code ([`mo`]) based on arbitrary user input. Determination is done using intelligent rules and the complete taxonomic tree of the kingdoms `r vector_and(unique(microorganisms$kingdom[which(!grepl("(unknown|Fungi)", microorganisms$kingdom))]), quotes = FALSE)`, and most microbial species from the kingdom Fungi (see *Source*). The input can be almost anything: a full name (like `"Staphylococcus aureus"`), an abbreviated name (such as `"S. aureus"`), an abbreviation known in the field (such as `"MRSA"`), or just a genus. See *Examples*. #' @param x a [character] vector or a [data.frame] with one or two columns #' @param Becker a [logical] to indicate whether staphylococci should be categorised into coagulase-negative staphylococci ("CoNS") and coagulase-positive staphylococci ("CoPS") instead of their own species, according to Karsten Becker *et al.* (see *Source*). Please see *Details* for a full list of staphylococcal species that will be converted. #' #' This excludes *Staphylococcus aureus* at default, use `Becker = "all"` to also categorise *S. aureus* as "CoPS". #' @param Lancefield a [logical] to indicate whether a beta-haemolytic *Streptococcus* should be categorised into Lancefield groups instead of their own species, according to Rebecca C. Lancefield (see *Source*). These streptococci will be categorised in their first group, e.g. *Streptococcus dysgalactiae* will be group C, although officially it was also categorised into groups G and L. . Please see *Details* for a full list of streptococcal species that will be converted. #' #' This excludes enterococci at default (who are in group D), use `Lancefield = "all"` to also categorise all enterococci as group D. #' @param minimum_matching_score a numeric value to set as the lower limit for the [MO matching score][mo_matching_score()]. When left blank, this will be determined automatically based on the character length of `x`, its [taxonomic kingdom][microorganisms] and [human pathogenicity][mo_matching_score()]. #' @param keep_synonyms a [logical] to indicate if old, previously valid taxonomic names must be preserved and not be corrected to currently accepted names. The default is `FALSE`, which will return a note if old taxonomic names were processed. The default can be set with the [package option][AMR-options] [`AMR_keep_synonyms`][AMR-options], i.e. `options(AMR_keep_synonyms = TRUE)` or `options(AMR_keep_synonyms = FALSE)`. #' @param reference_df a [data.frame] to be used for extra reference when translating `x` to a valid [`mo`]. See [set_mo_source()] and [get_mo_source()] to automate the usage of your own codes (e.g. used in your analysis or organisation). #' @param ignore_pattern a Perl-compatible [regular expression][base::regex] (case-insensitive) of which all matches in `x` must return `NA`. This can be convenient to exclude known non-relevant input and can also be set with the [package option][AMR-options] [`AMR_ignore_pattern`][AMR-options], e.g. `options(AMR_ignore_pattern = "(not reported|contaminated flora)")`. #' @param cleaning_regex a Perl-compatible [regular expression][base::regex] (case-insensitive) to clean the input of `x`. Every matched part in `x` will be removed. At default, this is the outcome of [mo_cleaning_regex()], which removes texts between brackets and texts such as "species" and "serovar". The default can be set with the [package option][AMR-options] [`AMR_cleaning_regex`][AMR-options]. #' @param language language to translate text like "no growth", which defaults to the system language (see [get_AMR_locale()]) #' @param info a [logical] to indicate if a progress bar should be printed if more than 25 items are to be coerced - the default is `TRUE` only in interactive mode #' @param ... other arguments passed on to functions #' @rdname as.mo #' @aliases mo #' @details #' A microorganism (MO) code from this package (class: [`mo`]) is human readable and typically looks like these examples: #' ``` #' Code Full name #' --------------- -------------------------------------- #' B_KLBSL Klebsiella #' B_KLBSL_PNMN Klebsiella pneumoniae #' B_KLBSL_PNMN_RHNS Klebsiella pneumoniae rhinoscleromatis #' | | | | #' | | | | #' | | | \---> subspecies, a 3-5 letter acronym #' | | \----> species, a 3-6 letter acronym #' | \----> genus, a 4-8 letter acronym #' \----> taxonomic kingdom: A (Archaea), AN (Animalia), B (Bacteria), #' F (Fungi), PL (Plantae), P (Protozoa) #' ``` #' #' Values that cannot be coerced will be considered 'unknown' and will be returned as the MO code `UNKNOWN` with a warning. #' #' Use the [`mo_*`][mo_property()] functions to get properties based on the returned code, see *Examples*. #' #' The [as.mo()] function uses a novel [matching score algorithm][mo_matching_score()] (see *Matching Score for Microorganisms* below) to match input against the [available microbial taxonomy][microorganisms] in this package. This will lead to the effect that e.g. `"E. coli"` (a microorganism highly prevalent in humans) will return the microbial ID of *Escherichia coli* and not *Entamoeba coli* (a microorganism less prevalent in humans), although the latter would alphabetically come first. #' #' With `Becker = TRUE`, the following `r length(MO_CONS[MO_CONS != "B_STPHY_CONS"])` staphylococci will be converted to the **coagulase-negative group**: `r vector_and(gsub("Staphylococcus", "S.", mo_name(MO_CONS[MO_CONS != "B_STPHY_CONS"], keep_synonyms = TRUE)), quotes = "*")`.\cr The following `r length(MO_COPS[MO_COPS != "B_STPHY_COPS"])` staphylococci will be converted to the **coagulase-positive group**: `r vector_and(gsub("Staphylococcus", "S.", mo_name(MO_COPS[MO_COPS != "B_STPHY_COPS"], keep_synonyms = TRUE)), quotes = "*")`. #' #' With `Lancefield = TRUE`, the following streptococci will be converted to their corresponding Lancefield group: `r vector_and(gsub("Streptococcus", "S.", paste0("*", mo_name(MO_LANCEFIELD, keep_synonyms = TRUE), "* (", mo_species(MO_LANCEFIELD, keep_synonyms = TRUE, Lancefield = TRUE), ")")), quotes = FALSE)`. #' #' ### Coping with Uncertain Results #' #' Results of non-exact taxonomic input are based on their [matching score][mo_matching_score()]. The lowest allowed score can be set with the `minimum_matching_score` argument. At default this will be determined based on the character length of the input, and the [taxonomic kingdom][microorganisms] and [human pathogenicity][mo_matching_score()] of the taxonomic outcome. If values are matched with uncertainty, a message will be shown to suggest the user to evaluate the results with [mo_uncertainties()], which returns a [data.frame] with all specifications. #' #' To increase the quality of matching, the `cleaning_regex` argument can be used to clean the input (i.e., `x`). This must be a [regular expression][base::regex] that matches parts of the input that should be removed before the input is matched against the [available microbial taxonomy][microorganisms]. It will be matched Perl-compatible and case-insensitive. The default value of `cleaning_regex` is the outcome of the helper function [mo_cleaning_regex()]. #' #' There are three helper functions that can be run after using the [as.mo()] function: #' - Use [mo_uncertainties()] to get a [data.frame] that prints in a pretty format with all taxonomic names that were guessed. The output contains the matching score for all matches (see *Matching Score for Microorganisms* below). #' - Use [mo_failures()] to get a [character] [vector] with all values that could not be coerced to a valid value. #' - Use [mo_renamed()] to get a [data.frame] with all values that could be coerced based on old, previously accepted taxonomic names. #' #' ### Microbial Prevalence of Pathogens in Humans #' #' The coercion rules consider the prevalence of microorganisms in humans, which is available as the `prevalence` column in the [microorganisms] data set. The grouping into human pathogenic prevalence is explained in the section *Matching Score for Microorganisms* below. #' @inheritSection mo_matching_score Matching Score for Microorganisms #' # (source as a section here, so it can be inherited by other man pages) #' @section Source: #' 1. Berends MS *et al.* (2022). **AMR: An R Package for Working with Antimicrobial Resistance Data**. *Journal of Statistical Software*, 104(3), 1-31; \doi{10.18637/jss.v104.i03} #' 2. Becker K *et al.* (2014). **Coagulase-Negative Staphylococci.** *Clin Microbiol Rev.* 27(4): 870-926; \doi{10.1128/CMR.00109-13} #' 3. Becker K *et al.* (2019). **Implications of identifying the recently defined members of the *S. aureus* complex, *S. argenteus* and *S. schweitzeri*: A position paper of members of the ESCMID Study Group for staphylococci and Staphylococcal Diseases (ESGS).** *Clin Microbiol Infect*; \doi{10.1016/j.cmi.2019.02.028} #' 4. Becker K *et al.* (2020). **Emergence of coagulase-negative staphylococci.** *Expert Rev Anti Infect Ther.* 18(4):349-366; \doi{10.1080/14787210.2020.1730813} #' 5. Lancefield RC (1933). **A serological differentiation of human and other groups of hemolytic streptococci.** *J Exp Med.* 57(4): 571-95; \doi{10.1084/jem.57.4.571} #' 6. Berends MS *et al.* (2022). **Trends in Occurrence and Phenotypic Resistance of Coagulase-Negative Staphylococci (CoNS) Found in Human Blood in the Northern Netherlands between 2013 and 2019/** *Micro.rganisms* 10(9), 1801; \doi{10.3390/microorganisms10091801} #' 7. `r TAXONOMY_VERSION$LPSN$citation` Accessed from <`r TAXONOMY_VERSION$LPSN$url`> on `r documentation_date(TAXONOMY_VERSION$LPSN$accessed_date)`. #' 8. `r TAXONOMY_VERSION$GBIF$citation` Accessed from <`r TAXONOMY_VERSION$GBIF$url`> on `r documentation_date(TAXONOMY_VERSION$GBIF$accessed_date)`. #' 9. `r TAXONOMY_VERSION$BacDive$citation` Accessed from <`r TAXONOMY_VERSION$BacDive$url`> on `r documentation_date(TAXONOMY_VERSION$BacDive$accessed_date)`. #' 10. `r TAXONOMY_VERSION$SNOMED$citation` URL: <`r TAXONOMY_VERSION$SNOMED$url`> #' 11. Bartlett A *et al.* (2022). **A comprehensive list of bacterial pathogens infecting humans** *Microbiology* 168:001269; \doi{10.1099/mic.0.001269} #' @export #' @return A [character] [vector] with additional class [`mo`] #' @seealso [microorganisms] for the [data.frame] that is being used to determine ID's. #' #' The [`mo_*`][mo_property()] functions (such as [mo_genus()], [mo_gramstain()]) to get properties based on the returned code. #' @inheritSection AMR Reference Data Publicly Available #' @examples #' \donttest{ #' # These examples all return "B_STPHY_AURS", the ID of S. aureus: #' as.mo(c( #' "sau", # WHONET code #' "stau", #' "STAU", #' "staaur", #' "S. aureus", #' "S aureus", #' "Sthafilokkockus aureus", # handles incorrect spelling #' "Staphylococcus aureus (MRSA)", #' "MRSA", # Methicillin Resistant S. aureus #' "VISA", # Vancomycin Intermediate S. aureus #' "VRSA", # Vancomycin Resistant S. aureus #' 115329001 # SNOMED CT code #' )) #' #' # Dyslexia is no problem - these all work: #' as.mo(c( #' "Ureaplasma urealyticum", #' "Ureaplasma urealyticus", #' "Ureaplasmium urealytica", #' "Ureaplazma urealitycium" #' )) #' #' # input will get cleaned up with the input given in the `cleaning_regex` argument, #' # which defaults to `mo_cleaning_regex()`: #' cat(mo_cleaning_regex(), "\n") #' #' as.mo("Streptococcus group A") #' #' as.mo("S. epidermidis") # will remain species: B_STPHY_EPDR #' as.mo("S. epidermidis", Becker = TRUE) # will not remain species: B_STPHY_CONS #' #' as.mo("S. pyogenes") # will remain species: B_STRPT_PYGN #' as.mo("S. pyogenes", Lancefield = TRUE) # will not remain species: B_STRPT_GRPA #' #' # All mo_* functions use as.mo() internally too (see ?mo_property): #' mo_genus("E. coli") #' mo_gramstain("ESCO") #' mo_is_intrinsic_resistant("ESCCOL", ab = "vanco") #' } as.mo <- function(x, Becker = FALSE, Lancefield = FALSE, minimum_matching_score = NULL, keep_synonyms = getOption("AMR_keep_synonyms", FALSE), reference_df = get_mo_source(), ignore_pattern = getOption("AMR_ignore_pattern", NULL), cleaning_regex = getOption("AMR_cleaning_regex", mo_cleaning_regex()), language = get_AMR_locale(), info = interactive(), ...) { meet_criteria(x, allow_class = c("mo", "data.frame", "list", "character", "numeric", "integer", "factor"), allow_NA = TRUE) meet_criteria(Becker, allow_class = c("logical", "character"), has_length = 1) meet_criteria(Lancefield, allow_class = c("logical", "character"), has_length = 1) meet_criteria(minimum_matching_score, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) meet_criteria(reference_df, allow_class = "data.frame", allow_NULL = TRUE) meet_criteria(ignore_pattern, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(cleaning_regex, allow_class = "character", has_length = 1, allow_NULL = TRUE) language <- validate_language(language) meet_criteria(info, allow_class = "logical", has_length = 1) add_MO_lookup_to_AMR_env() if (tryCatch(all(x %in% c(AMR_env$MO_lookup$mo, NA)), error = function(e) FALSE) && isFALSE(Becker) && isFALSE(Lancefield) && isTRUE(keep_synonyms)) { # don't look into valid MO codes, just return them # is.mo() won't work - MO codes might change between package versions return(set_clean_class(x, new_class = c("mo", "character"))) } # start off with replaced language-specific non-ASCII characters with ASCII characters x <- parse_and_convert(x) # replace mo codes used in older package versions x <- replace_old_mo_codes(x, property = "mo") # ignore cases that match the ignore pattern x <- replace_ignore_pattern(x, ignore_pattern) x_lower <- tolower(x) # WHONET: xxx = no growth x[x_lower %in% c("", "xxx", "na", "nan")] <- NA_character_ out <- rep(NA_character_, length(x)) # below we use base R's match(), known for powering '%in%', and incredibly fast! # From reference_df ---- reference_df <- repair_reference_df(reference_df) if (!is.null(reference_df)) { out[x %in% reference_df[[1]]] <- reference_df[[2]][match(x[x %in% reference_df[[1]]], reference_df[[1]])] } # From MO code ---- out[is.na(out) & toupper(x) %in% AMR_env$MO_lookup$mo] <- toupper(x[is.na(out) & toupper(x) %in% AMR_env$MO_lookup$mo]) # From full name ---- out[is.na(out) & x_lower %in% AMR_env$MO_lookup$fullname_lower] <- AMR_env$MO_lookup$mo[match(x_lower[is.na(out) & x_lower %in% AMR_env$MO_lookup$fullname_lower], AMR_env$MO_lookup$fullname_lower)] # one exception: "Fungi" matches the kingdom, but instead it should return the 'unknown' code for fungi out[out == "F_[KNG]_FUNGI"] <- "F_FUNGUS" # From known codes ---- out[is.na(out) & toupper(x) %in% AMR::microorganisms.codes$code] <- AMR::microorganisms.codes$mo[match(toupper(x)[is.na(out) & toupper(x) %in% AMR::microorganisms.codes$code], AMR::microorganisms.codes$code)] # From SNOMED ---- # based on this extremely fast gem: https://stackoverflow.com/a/11002456/4575331 snomeds <- unlist(AMR_env$MO_lookup$snomed) snomeds <- snomeds[!is.na(snomeds)] out[is.na(out) & x %in% snomeds] <- AMR_env$MO_lookup$mo[rep(seq_along(AMR_env$MO_lookup$snomed), vapply(FUN.VALUE = double(1), AMR_env$MO_lookup$snomed, length))[match(x[is.na(out) & x %in% snomeds], snomeds)]] # From other familiar output ---- # such as Salmonella groups, colloquial names, etc. out[is.na(out)] <- convert_colloquial_input(x[is.na(out)]) # From previous hits in this session ---- old <- out out[is.na(out) & paste(x, minimum_matching_score) %in% AMR_env$mo_previously_coerced$x] <- AMR_env$mo_previously_coerced$mo[match(paste(x, minimum_matching_score)[is.na(out) & paste(x, minimum_matching_score) %in% AMR_env$mo_previously_coerced$x], AMR_env$mo_previously_coerced$x)] new <- out if (isTRUE(info) && message_not_thrown_before("as.mo", old, new, entire_session = TRUE) && any(is.na(old) & !is.na(new), na.rm = TRUE)) { message_( "Returning previously coerced value", ifelse(sum(is.na(old) & !is.na(new)) > 1, "s", ""), " for ", vector_and(x[is.na(old) & !is.na(new)]), ". Run `mo_reset_session()` to reset this. This note will be shown once per session for this input." ) } # For all other input ---- if (any(is.na(out) & !is.na(x))) { # reset uncertainties AMR_env$mo_uncertainties <- AMR_env$mo_uncertainties[0, ] AMR_env$mo_failures <- NULL # Laboratory systems: remove (translated) entries like "no growth", "not E. coli", etc. x[trimws2(x) %like% translate_into_language("no .*growth", language = language)] <- NA_character_ x[trimws2(x) %like% paste0("^(", translate_into_language("no|not", language = language), ") ")] <- NA_character_ # groups are in our taxonomic table with a capital G x <- gsub(" group( |$)", " Group\\1", x, perl = TRUE) # run over all unique leftovers x_unique <- unique(x[is.na(out) & !is.na(x)]) # set up progress bar progress <- progress_ticker(n = length(x_unique), n_min = 10, print = info) on.exit(close(progress)) msg <- character(0) # run it x_coerced <- vapply(FUN.VALUE = character(1), x_unique, function(x_search) { progress$tick() # some required cleaning steps x_out <- trimws2(x_search) # this applies the `cleaning_regex` argument, which defaults to mo_cleaning_regex() x_out <- gsub(cleaning_regex, " ", x_out, ignore.case = TRUE, perl = TRUE) x_out <- trimws2(gsub(" +", " ", x_out, perl = TRUE)) x_search_cleaned <- x_out x_out <- tolower(x_out) # when x_search_cleaned are only capitals (such as in codes), make them lowercase to increase matching score x_search_cleaned[x_search_cleaned == toupper(x_search_cleaned)] <- x_out[x_search_cleaned == toupper(x_search_cleaned)] # first check if cleaning led to an exact result, case-insensitive if (x_out %in% AMR_env$MO_lookup$fullname_lower) { return(as.character(AMR_env$MO_lookup$mo[match(x_out, AMR_env$MO_lookup$fullname_lower)])) } # input must not be too short if (nchar(x_out) < 3) { return("UNKNOWN") } # take out the parts, split by space x_parts <- strsplit(gsub("-", " ", x_out, fixed = TRUE), " ", fixed = TRUE)[[1]] # do a pre-match on first character (and if it contains a space, first chars of first two terms) if (length(x_parts) %in% c(2, 3)) { # for genus + species + subspecies if (nchar(gsub("[^a-z]", "", x_parts[1], perl = TRUE)) <= 3) { filtr <- which(AMR_env$MO_lookup$full_first == substr(x_parts[1], 1, 1) & (AMR_env$MO_lookup$species_first == substr(x_parts[2], 1, 1) | AMR_env$MO_lookup$subspecies_first == substr(x_parts[2], 1, 1) | AMR_env$MO_lookup$subspecies_first == substr(x_parts[3], 1, 1))) } else { filtr <- which(AMR_env$MO_lookup$full_first == substr(x_parts[1], 1, 1) | AMR_env$MO_lookup$species_first == substr(x_parts[2], 1, 1) | AMR_env$MO_lookup$subspecies_first == substr(x_parts[2], 1, 1) | AMR_env$MO_lookup$subspecies_first == substr(x_parts[3], 1, 1)) } } else if (length(x_parts) > 3) { first_chars <- paste0("(^| )[", paste(substr(x_parts, 1, 1), collapse = ""), "]") filtr <- which(AMR_env$MO_lookup$full_first %like_case% first_chars) } else if (nchar(x_out) == 3) { # no space and 3 characters - probably a code such as SAU or ECO msg <<- c(msg, paste0("Input \"", x_search, "\" was assumed to be a microorganism code - tried to match on \"", totitle(substr(x_out, 1, 1)), AMR_env$dots, " ", substr(x_out, 2, 3), AMR_env$dots, "\"")) filtr <- which(AMR_env$MO_lookup$fullname_lower %like_case% paste0("(^| )", substr(x_out, 1, 1), ".* ", substr(x_out, 2, 3))) } else if (nchar(x_out) == 4) { # no space and 4 characters - probably a code such as STAU or ESCO msg <<- c(msg, paste0("Input \"", x_search, "\" was assumed to be a microorganism code - tried to match on \"", totitle(substr(x_out, 1, 2)), AMR_env$dots, " ", substr(x_out, 3, 4), AMR_env$dots, "\"")) filtr <- which(AMR_env$MO_lookup$fullname_lower %like_case% paste0("(^| )", substr(x_out, 1, 2), ".* ", substr(x_out, 3, 4))) } else if (nchar(x_out) <= 6) { # no space and 5-6 characters - probably a code such as STAAUR or ESCCOL first_part <- paste0(substr(x_out, 1, 2), "[a-z]*", substr(x_out, 3, 3)) second_part <- substr(x_out, 4, nchar(x_out)) msg <<- c(msg, paste0("Input \"", x_search, "\" was assumed to be a microorganism code - tried to match on \"", gsub("[a-z]*", AMR_env$dots, totitle(first_part), fixed = TRUE), " ", second_part, AMR_env$dots, "\"")) filtr <- which(AMR_env$MO_lookup$fullname_lower %like_case% paste0("(^| )", first_part, ".* ", second_part)) } else { # for genus or species or subspecies filtr <- which(AMR_env$MO_lookup$full_first == substr(x_parts, 1, 1) | AMR_env$MO_lookup$species_first == substr(x_parts, 1, 1) | AMR_env$MO_lookup$subspecies_first == substr(x_parts, 1, 1)) } if (length(filtr) == 0) { mo_to_search <- AMR_env$MO_lookup$fullname } else { mo_to_search <- AMR_env$MO_lookup$fullname[filtr] } AMR_env$mo_to_search <- mo_to_search # determine the matching score on the original search value m <- mo_matching_score(x = x_search_cleaned, n = mo_to_search) if (is.null(minimum_matching_score)) { minimum_matching_score_current <- min(0.6, min(10, nchar(x_search_cleaned)) * 0.08) # correct back for prevalence minimum_matching_score_current <- minimum_matching_score_current / AMR_env$MO_lookup$prevalence[match(mo_to_search, AMR_env$MO_lookup$fullname)] # correct back for kingdom minimum_matching_score_current <- minimum_matching_score_current / AMR_env$MO_lookup$kingdom_index[match(mo_to_search, AMR_env$MO_lookup$fullname)] minimum_matching_score_current <- pmax(minimum_matching_score_current, m) if (length(x_parts) > 1 && all(m <= 0.55, na.rm = TRUE)) { # if the highest score is 0.5, we have nothing serious - 0.5 is the lowest for pathogenic group 1 # make everything NA so the results will get removed below # (we added length(x_parts) > 1 to exclude microbial codes from this rule, such as "STAU") m[seq_len(length(m))] <- NA_real_ } } else { # minimum_matching_score was set, so remove everything below it m[m < minimum_matching_score] <- NA_real_ minimum_matching_score_current <- minimum_matching_score } top_hits <- mo_to_search[order(m, decreasing = TRUE, na.last = NA)] # na.last = NA will remove the NAs if (length(top_hits) == 0) { warning_("No hits found for \"", x_search, "\" with minimum_matching_score = ", ifelse(is.null(minimum_matching_score), paste0("NULL (=", round(min(minimum_matching_score_current, na.rm = TRUE), 3), ")"), minimum_matching_score), ". Try setting this value lower or even to 0.", call = FALSE) result_mo <- NA_character_ } else { result_mo <- AMR_env$MO_lookup$mo[match(top_hits[1], AMR_env$MO_lookup$fullname)] AMR_env$mo_uncertainties <- rbind_AMR( AMR_env$mo_uncertainties, data.frame( original_input = x_search, input = x_search_cleaned, fullname = top_hits[1], mo = result_mo, candidates = ifelse(length(top_hits) > 1, paste(top_hits[2:min(99, length(top_hits))], collapse = ", "), ""), minimum_matching_score = ifelse(is.null(minimum_matching_score), "NULL", minimum_matching_score), keep_synonyms = keep_synonyms, stringsAsFactors = FALSE ) ) # save to package env to save time for next time AMR_env$mo_previously_coerced <- unique(rbind_AMR( AMR_env$mo_previously_coerced, data.frame( x = paste(x_search, minimum_matching_score), mo = result_mo, stringsAsFactors = FALSE ) )) } # the actual result: as.character(result_mo) }) # remove progress bar from console close(progress) # expand from unique again out[is.na(out)] <- x_coerced[match(x[is.na(out)], x_unique)] # Throw note about uncertainties ---- if (isTRUE(info) && NROW(AMR_env$mo_uncertainties) > 0) { if (message_not_thrown_before("as.mo", "uncertainties", AMR_env$mo_uncertainties$original_input)) { plural <- c("", "this") if (length(AMR_env$mo_uncertainties$original_input) > 1) { plural <- c("s", "these uncertainties") } if (length(AMR_env$mo_uncertainties$original_input) <= 3) { examples <- vector_and( paste0( '"', AMR_env$mo_uncertainties$original_input, '" (assumed ', italicise(AMR_env$mo_uncertainties$fullname), ")" ), quotes = FALSE ) } else { examples <- paste0(nr2char(length(AMR_env$mo_uncertainties$original_input)), " microorganism", plural[1]) } msg <- c(msg, paste0( "Microorganism translation was uncertain for ", examples, ". Run `mo_uncertainties()` to review ", plural[2], ", or use `add_custom_microorganisms()` to add custom entries." )) for (m in msg) { message_(m) } } } } # end of loop over all yet unknowns # Keep or replace synonyms ---- lpsn_matches <- AMR_env$MO_lookup$lpsn_renamed_to[match(out, AMR_env$MO_lookup$mo)] lpsn_matches[!lpsn_matches %in% AMR_env$MO_lookup$lpsn] <- NA # GBIF only for non-bacteria, since we use LPSN as primary source for bacteria # (an example is Strep anginosus, renamed according to GBIF, not according to LPSN) gbif_matches <- AMR_env$MO_lookup$gbif_renamed_to[AMR_env$MO_lookup$kingdom != "Bacteria"][match(out, AMR_env$MO_lookup$mo[AMR_env$MO_lookup$kingdom != "Bacteria"])] gbif_matches[!gbif_matches %in% AMR_env$MO_lookup$gbif] <- NA AMR_env$mo_renamed <- list( old = out[!is.na(gbif_matches) | !is.na(lpsn_matches)], gbif_matches = gbif_matches[!is.na(gbif_matches) | !is.na(lpsn_matches)], lpsn_matches = lpsn_matches[!is.na(gbif_matches) | !is.na(lpsn_matches)] ) if (isFALSE(keep_synonyms)) { out[which(!is.na(gbif_matches))] <- AMR_env$MO_lookup$mo[match(gbif_matches[which(!is.na(gbif_matches))], AMR_env$MO_lookup$gbif)] out[which(!is.na(lpsn_matches))] <- AMR_env$MO_lookup$mo[match(lpsn_matches[which(!is.na(lpsn_matches))], AMR_env$MO_lookup$lpsn)] if (isTRUE(info) && length(AMR_env$mo_renamed$old) > 0) { print(mo_renamed(), extra_txt = " (use `keep_synonyms = TRUE` to leave uncorrected)") } } else if (is.null(getOption("AMR_keep_synonyms")) && length(AMR_env$mo_renamed$old) > 0 && message_not_thrown_before("as.mo", "keep_synonyms_warning", entire_session = TRUE)) { # keep synonyms is TRUE, so check if any do have synonyms warning_("Function `as.mo()` returned ", nr2char(length(unique(AMR_env$mo_renamed$old))), " old taxonomic name", ifelse(length(unique(AMR_env$mo_renamed$old)) > 1, "s", ""), ". Use `as.mo(..., keep_synonyms = FALSE)` to clean the input to currently accepted taxonomic names, or set the R option `AMR_keep_synonyms` to `FALSE`. This warning will be shown once per session.", call = FALSE) } # Apply Becker ---- if (isTRUE(Becker) || Becker == "all") { # warn when species found that are not in: # - Becker et al. 2014, PMID 25278577 # - Becker et al. 2019, PMID 30872103 # - Becker et al. 2020, PMID 32056452 # comment below code if all staphylococcal species are categorised as CoNS/CoPS post_Becker <- paste( "Staphylococcus", c("caledonicus", "canis", "durrellii", "lloydii", "ratti", "roterodami", "singaporensis", "taiwanensis") ) if (any(out %in% AMR_env$MO_lookup$mo[match(post_Becker, AMR_env$MO_lookup$fullname)])) { if (message_not_thrown_before("as.mo", "becker")) { warning_("in `as.mo()`: Becker ", font_italic("et al."), " (2014, 2019, 2020) does not contain these species named after their publication: ", vector_and(font_italic(gsub("Staphylococcus", "S.", post_Becker, fixed = TRUE), collapse = NULL), quotes = FALSE), ". Categorisation to CoNS/CoPS was taken from the original scientific publication(s).", immediate = TRUE, call = FALSE ) } } # 'MO_CONS' and 'MO_COPS' are 'mo' vectors created in R/_pre_commit_hook.R out[out %in% MO_CONS] <- "B_STPHY_CONS" out[out %in% MO_COPS] <- "B_STPHY_COPS" if (Becker == "all") { out[out == "B_STPHY_AURS"] <- "B_STPHY_COPS" } } # Apply Lancefield ---- if (isTRUE(Lancefield) || Lancefield == "all") { # (using `%like_case%` to also match subspecies) # group A - S. pyogenes out[out %like_case% "^B_STRPT_PYGN(_|$)"] <- "B_STRPT_GRPA" # group B - S. agalactiae out[out %like_case% "^B_STRPT_AGLC(_|$)"] <- "B_STRPT_GRPB" # group C - all subspecies within S. dysgalactiae and S. equi (such as S. equi zooepidemicus) out[out %like_case% "^B_STRPT_(DYSG|EQUI)(_|$)"] <- "B_STRPT_GRPC" if (Lancefield == "all") { # group D - all enterococci out[out %like_case% "^B_ENTRC(_|$)"] <- "B_STRPT_GRPD" } # group F - Milleri group == S. anginosus group, which incl. S. anginosus, S. constellatus, S. intermedius out[out %like_case% "^B_STRPT_(ANGN|CNST|INTR)(_|$)"] <- "B_STRPT_GRPF" # group G - S. dysgalactiae and S. canis (though dysgalactiae is also group C and will be matched there) out[out %like_case% "^B_STRPT_(DYSG|CANS)(_|$)"] <- "B_STRPT_GRPG" # group H - S. sanguinis out[out %like_case% "^B_STRPT_SNGN(_|$)"] <- "B_STRPT_GRPH" # group K - S. salivarius, incl. S. salivarius salivarius and S. salivarius thermophilus out[out %like_case% "^B_STRPT_SLVR(_|$)"] <- "B_STRPT_GRPK" # group L - only S. dysgalactiae which is also group C & G, so ignore it here } # All unknowns ---- out[is.na(out) & !is.na(x)] <- "UNKNOWN" AMR_env$mo_failures <- unique(x[out == "UNKNOWN" & !toupper(x) %in% c("UNKNOWN", "CON", "UNK") & !x %like_case% "^[(]unknown [a-z]+[)]$" & !is.na(x)]) if (length(AMR_env$mo_failures) > 0) { warning_("The following input could not be coerced and was returned as \"UNKNOWN\": ", vector_and(AMR_env$mo_failures, quotes = TRUE), ".\nYou can retrieve this list with `mo_failures()`.", call = FALSE) } # Return class ---- set_clean_class(out, new_class = c("mo", "character") ) } # OTHER DOCUMENTED FUNCTIONS ---------------------------------------------- #' @rdname as.mo #' @export is.mo <- function(x) { inherits(x, "mo") } #' @rdname as.mo #' @export mo_uncertainties <- function() { set_clean_class(AMR_env$mo_uncertainties, new_class = c("mo_uncertainties", "data.frame")) } #' @rdname as.mo #' @export mo_renamed <- function() { add_MO_lookup_to_AMR_env() x <- AMR_env$mo_renamed x$new <- synonym_mo_to_accepted_mo(x$old) mo_old <- AMR_env$MO_lookup$fullname[match(x$old, AMR_env$MO_lookup$mo)] mo_new <- AMR_env$MO_lookup$fullname[match(x$new, AMR_env$MO_lookup$mo)] ref_old <- AMR_env$MO_lookup$ref[match(x$old, AMR_env$MO_lookup$mo)] ref_new <- AMR_env$MO_lookup$ref[match(x$new, AMR_env$MO_lookup$mo)] df_renamed <- data.frame( old = mo_old, new = mo_new, ref_old = ref_old, ref_new = ref_new, stringsAsFactors = FALSE ) df_renamed <- unique(df_renamed) df_renamed <- df_renamed[order(df_renamed$old), , drop = FALSE] set_clean_class(df_renamed, new_class = c("mo_renamed", "data.frame")) } #' @rdname as.mo #' @export mo_failures <- function() { AMR_env$mo_failures } #' @rdname as.mo #' @export mo_reset_session <- function() { if (NROW(AMR_env$mo_previously_coerced) > 0) { message_("Reset ", nr2char(NROW(AMR_env$mo_previously_coerced)), " previously matched input value", ifelse(NROW(AMR_env$mo_previously_coerced) > 1, "s", ""), ".") AMR_env$mo_previously_coerced <- AMR_env$mo_previously_coerced[0, , drop = FALSE] AMR_env$mo_uncertainties <- AMR_env$mo_uncertainties[0, , drop = FALSE] } else { message_("No previously matched input values to reset.") } } #' @rdname as.mo #' @export mo_cleaning_regex <- function() { parts_to_remove <- c("e?spp([^a-z]+|$)", "e?ssp([^a-z]+|$)", "e?ss([^a-z]+|$)", "e?sp([^a-z]+|$)", "e?subsp", "sube?species", "e?species", "biovar[a-z]*", "biotype", "serovar[a-z]*", "var([^a-z]+|$)", "serogr.?up[a-z]*", "titer", "dummy", "Ig[ADEGM]") paste0( "(", "[^A-Za-z- \\(\\)\\[\\]{}]+", "|", "([({]|\\[).+([})]|\\])", "|(^| )(", paste0(parts_to_remove[order(1 - nchar(parts_to_remove))], collapse = "|"), "))") } # UNDOCUMENTED METHODS ---------------------------------------------------- # will be exported using s3_register() in R/zzz.R pillar_shaft.mo <- function(x, ...) { add_MO_lookup_to_AMR_env() out <- trimws(format(x)) # grey out the kingdom (part until first "_") out[!is.na(x)] <- gsub("^([A-Z]+_)(.*)", paste0(font_subtle("\\1"), "\\2"), out[!is.na(x)], perl = TRUE) # and grey out every _ out[!is.na(x)] <- gsub("_", font_subtle("_"), out[!is.na(x)]) # markup NA and UNKNOWN out[is.na(x)] <- font_na(" NA") out[x == "UNKNOWN"] <- font_na(" UNKNOWN") # markup manual codes out[x %in% AMR_env$MO_lookup$mo & !x %in% AMR::microorganisms$mo] <- font_blue(out[x %in% AMR_env$MO_lookup$mo & !x %in% AMR::microorganisms$mo], collapse = NULL) df <- tryCatch(get_current_data(arg_name = "x", call = 0), error = function(e) NULL ) if (!is.null(df)) { mo_cols <- vapply(FUN.VALUE = logical(1), df, is.mo) } else { mo_cols <- NULL } all_mos <- c(AMR_env$MO_lookup$mo, NA) if (!all(x %in% all_mos) || (!is.null(df) && !all(unlist(df[, which(mo_cols), drop = FALSE]) %in% all_mos))) { # markup old mo codes out[!x %in% all_mos] <- font_italic( font_na(x[!x %in% all_mos], collapse = NULL ), collapse = NULL ) # throw a warning with the affected column name(s) if (!is.null(mo_cols)) { col <- paste0("Column ", vector_or(colnames(df)[mo_cols], quotes = TRUE, sort = FALSE)) } else { col <- "The data" } warning_( col, " contains old MO codes (from a previous AMR package version). ", "Please update your MO codes with `as.mo()`.", call = FALSE ) } # add the names to the bugs as mouse-over! if (tryCatch(isTRUE(getExportedValue("ansi_has_hyperlink_support", ns = asNamespace("cli"))()), error = function(e) FALSE)) { out[!x %in% c("UNKNOWN", NA)] <- font_url(url = paste0(x[!x %in% c("UNKNOWN", NA)], ": ", mo_name(x[!x %in% c("UNKNOWN", NA)], keep_synonyms = TRUE)), txt = out[!x %in% c("UNKNOWN", NA)]) } # make it always fit exactly max_char <- max(nchar(x)) if (is.na(max_char)) { max_char <- 12 } create_pillar_column(out, align = "left", width = max_char + ifelse(any(x %in% c(NA, "UNKNOWN")), 2, 0) ) } # will be exported using s3_register() in R/zzz.R type_sum.mo <- function(x, ...) { "mo" } # will be exported using s3_register() in R/zzz.R freq.mo <- function(x, ...) { x_noNA <- as.mo(x[!is.na(x)]) # as.mo() to get the newest mo codes grams <- mo_gramstain(x_noNA, language = NULL) digits <- list(...)$digits if (is.null(digits)) { digits <- 2 } cleaner::freq.default( x = x, ..., .add_header = list( `Gram-negative` = paste0( format(sum(grams == "Gram-negative", na.rm = TRUE), big.mark = " ", decimal.mark = "." ), " (", percentage(sum(grams == "Gram-negative", na.rm = TRUE) / length(grams), digits = digits ), ")" ), `Gram-positive` = paste0( format(sum(grams == "Gram-positive", na.rm = TRUE), big.mark = " ", decimal.mark = "." ), " (", percentage(sum(grams == "Gram-positive", na.rm = TRUE) / length(grams), digits = digits ), ")" ), `Nr. of genera` = pm_n_distinct(mo_genus(x_noNA, language = NULL)), `Nr. of species` = pm_n_distinct(paste( mo_genus(x_noNA, language = NULL), mo_species(x_noNA, language = NULL) )) ) ) } # will be exported using s3_register() in R/zzz.R get_skimmers.mo <- function(column) { skimr::sfl( skim_type = "mo", unique_total = ~ length(unique(stats::na.omit(.))), gram_negative = ~ sum(mo_is_gram_negative(.), na.rm = TRUE), gram_positive = ~ sum(mo_is_gram_positive(.), na.rm = TRUE), top_genus = ~ names(sort(-table(mo_genus(stats::na.omit(.), language = NULL))))[1L], top_species = ~ names(sort(-table(mo_name(stats::na.omit(.), language = NULL))))[1L] ) } #' @method print mo #' @export #' @noRd print.mo <- function(x, print.shortnames = FALSE, ...) { add_MO_lookup_to_AMR_env() cat("Class 'mo'\n") x_names <- names(x) if (is.null(x_names) & print.shortnames == TRUE) { x_names <- tryCatch(mo_shortname(x, ...), error = function(e) NULL) } x <- as.character(x) names(x) <- x_names if (!all(x %in% c(AMR_env$MO_lookup$mo, NA))) { warning_( "Some MO codes are from a previous AMR package version. ", "Please update the MO codes with `as.mo()`.", call = FALSE ) } print.default(x, quote = FALSE) } #' @method summary mo #' @export #' @noRd summary.mo <- function(object, ...) { # unique and top 1-3 x <- object top_3 <- names(sort(-table(x[!is.na(x)])))[1:3] out <- c( "Class" = "mo", "<NA>" = length(x[is.na(x)]), "Unique" = length(unique(x[!is.na(x)])), "#1" = top_3[1], "#2" = top_3[2], "#3" = top_3[3] ) class(out) <- c("summaryDefault", "table") out } #' @method as.data.frame mo #' @export #' @noRd as.data.frame.mo <- function(x, ...) { add_MO_lookup_to_AMR_env() if (!all(x %in% c(AMR_env$MO_lookup$mo, NA))) { warning_( "The data contains old MO codes (from a previous AMR package version). ", "Please update your MO codes with `as.mo()`." ) } nm <- deparse1(substitute(x)) if (!"nm" %in% names(list(...))) { as.data.frame.vector(x, ..., nm = nm) } else { as.data.frame.vector(x, ...) } } #' @method [ mo #' @export #' @noRd "[.mo" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [[ mo #' @export #' @noRd "[[.mo" <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method [<- mo #' @export #' @noRd "[<-.mo" <- function(i, j, ..., value) { y <- NextMethod() attributes(y) <- attributes(i) # must only contain valid MOs add_MO_lookup_to_AMR_env() return_after_integrity_check(y, "microorganism code", as.character(AMR_env$MO_lookup$mo)) } #' @method [[<- mo #' @export #' @noRd "[[<-.mo" <- function(i, j, ..., value) { y <- NextMethod() attributes(y) <- attributes(i) # must only contain valid MOs add_MO_lookup_to_AMR_env() return_after_integrity_check(y, "microorganism code", as.character(AMR_env$MO_lookup$mo)) } #' @method c mo #' @export #' @noRd c.mo <- function(...) { x <- list(...)[[1L]] y <- NextMethod() attributes(y) <- attributes(x) add_MO_lookup_to_AMR_env() return_after_integrity_check(y, "microorganism code", as.character(AMR_env$MO_lookup$mo)) } #' @method unique mo #' @export #' @noRd unique.mo <- function(x, incomparables = FALSE, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method rep mo #' @export #' @noRd rep.mo <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method print mo_uncertainties #' @export #' @noRd print.mo_uncertainties <- function(x, n = 10, ...) { more_than_50 <- FALSE if (NROW(x) == 0) { cat(word_wrap("No uncertainties to show. Only uncertainties of the last call to `as.mo()` or any `mo_*()` function are stored.\n\n", add_fn = font_blue)) return(invisible(NULL)) } else if (NROW(x) > 50) { more_than_50 <- TRUE x <- x[1:50, , drop = FALSE] } cat(word_wrap("Matching scores are based on the resemblance between the input and the full taxonomic name, and the pathogenicity in humans. See `?mo_matching_score`.\n\n", add_fn = font_blue)) add_MO_lookup_to_AMR_env() col_red <- function(x) font_rose_bg(x, collapse = NULL) col_orange <- function(x) font_orange_bg(x, collapse = NULL) col_yellow <- function(x) font_yellow_bg(x, collapse = NULL) col_green <- function(x) font_green_bg(x, collapse = NULL) if (has_colour()) { cat(word_wrap("Colour keys: ", col_red(" 0.000-0.549 "), col_orange(" 0.550-0.649 "), col_yellow(" 0.650-0.749 "), col_green(" 0.750-1.000"), add_fn = font_blue ), font_green_bg(" "), "\n", sep = "") } score_set_colour <- function(text, scores) { # set colours to scores text[scores >= 0.75] <- col_green(text[scores >= 0.75]) text[scores >= 0.65 & scores < 0.75] <- col_yellow(text[scores >= 0.65 & scores < 0.75]) text[scores >= 0.55 & scores < 0.65] <- col_orange(text[scores >= 0.55 & scores < 0.65]) text[scores < 0.55] <- col_red(text[scores < 0.55]) text } txt <- "" any_maxed_out <- FALSE for (i in seq_len(nrow(x))) { if (x[i, ]$candidates != "") { candidates <- unlist(strsplit(x[i, ]$candidates, ", ", fixed = TRUE)) if (length(candidates) > n) { any_maxed_out <- TRUE candidates <- candidates[seq_len(n)] } scores <- mo_matching_score(x = x[i, ]$input, n = candidates) n_candidates <- length(candidates) candidates_formatted <- italicise(candidates) scores_formatted <- trimws(formatC(round(scores, 3), format = "f", digits = 3)) scores_formatted <- score_set_colour(scores_formatted, scores) # sort on descending scores candidates_formatted <- candidates_formatted[order(1 - scores)] scores_formatted <- scores_formatted[order(1 - scores)] candidates <- word_wrap( paste0( "Also matched: ", vector_and( paste0( candidates_formatted, font_blue(paste0(" (", scores_formatted, ")"), collapse = NULL) ), quotes = FALSE, sort = FALSE ) ), extra_indent = nchar("Also matched: "), width = 0.9 * getOption("width", 100) ) } else { candidates <- "" } score <- mo_matching_score( x = x[i, ]$input, n = x[i, ]$fullname ) score_formatted <- trimws(formatC(round(score, 3), format = "f", digits = 3)) txt <- paste(txt, paste0( paste0( "", strrep(font_grey("-"), times = getOption("width", 100)), "\n", '"', x[i, ]$original_input, '"', " -> ", paste0( font_bold(italicise(x[i, ]$fullname)), " (", x[i, ]$mo, ", ", score_set_colour(score_formatted, score), ")" ) ), collapse = "\n" ), # Add note if result was coerced to accepted taxonomic name ifelse(x[i, ]$keep_synonyms == FALSE & x[i, ]$mo %in% AMR_env$MO_lookup$mo[which(AMR_env$MO_lookup$status == "synonym")], paste0( strrep(" ", nchar(x[i, ]$original_input) + 6), font_red(paste0("This old taxonomic name was converted to ", font_italic(AMR_env$MO_lookup$fullname[match(synonym_mo_to_accepted_mo(x[i, ]$mo), AMR_env$MO_lookup$mo)], collapse = NULL), " (", synonym_mo_to_accepted_mo(x[i, ]$mo), ")."), collapse = NULL) ), "" ), candidates, sep = "\n" ) txt <- gsub("[\n]+", "\n", txt) # remove first and last break txt <- gsub("(^[\n]|[\n]$)", "", txt) txt <- paste0("\n", txt, "\n") } cat(txt) if (isTRUE(any_maxed_out)) { cat(font_blue(word_wrap("\nOnly the first ", n, " other matches of each record are shown. Run `print(mo_uncertainties(), n = ...)` to view more entries, or save `mo_uncertainties()` to an object."))) } if (isTRUE(more_than_50)) { cat(font_blue(word_wrap("\nOnly the first 50 uncertainties are shown. Run `View(mo_uncertainties())` to view all entries, or save `mo_uncertainties()` to an object."))) } } #' @method print mo_renamed #' @export #' @noRd print.mo_renamed <- function(x, extra_txt = "", n = 25, ...) { if (NROW(x) == 0) { cat(word_wrap("No renamed taxonomy to show. Only renamed taxonomy of the last call of `as.mo()` or any `mo_*()` function are stored.\n", add_fn = font_blue)) return(invisible(NULL)) } x$ref_old[!is.na(x$ref_old)] <- paste0(" (", gsub("et al.", font_italic("et al."), x$ref_old[!is.na(x$ref_old)], fixed = TRUE), ")") x$ref_new[!is.na(x$ref_new)] <- paste0(" (", gsub("et al.", font_italic("et al."), x$ref_new[!is.na(x$ref_new)], fixed = TRUE), ")") x$ref_old[is.na(x$ref_old)] <- " (author unknown)" x$ref_new[is.na(x$ref_new)] <- " (author unknown)" rows <- seq_len(min(NROW(x), n)) message_( "The following microorganism", ifelse(NROW(x) > 1, "s were", " was"), " taxonomically renamed", extra_txt, ":\n", paste0(" ", AMR_env$bullet_icon, " ", font_italic(x$old[rows], collapse = NULL), x$ref_old[rows], " -> ", font_italic(x$new[rows], collapse = NULL), x$ref_new[rows], collapse = "\n" ), ifelse(NROW(x) > n, paste0("\n\nOnly the first ", n, " (out of ", NROW(x), ") are shown. Run `print(mo_renamed(), n = ...)` to view more entries (might be slow), or save `mo_renamed()` to an object."), "") ) } # UNDOCUMENTED HELPER FUNCTIONS ------------------------------------------- convert_colloquial_input <- function(x) { x.bak <- trimws2(x) x <- trimws2(tolower(x)) out <- rep(NA_character_, length(x)) # Streptococci, like GBS = Group B Streptococci (B_STRPT_GRPB) out[x %like_case% "^g[abcdefghijkl]s$"] <- gsub("g([abcdefghijkl])s", "B_STRPT_GRP\\U\\1", x[x %like_case% "^g[abcdefghijkl]s$"], perl = TRUE ) # Streptococci in different languages, like "estreptococos grupo B" out[x %like_case% "strepto[ck]o[ck][a-zA-Z ]* [abcdefghijkl]$"] <- gsub(".*e?strepto[ck]o[ck].* ([abcdefghijkl])$", "B_STRPT_GRP\\U\\1", x[x %like_case% "strepto[ck]o[ck][a-zA-Z ]* [abcdefghijkl]$"], perl = TRUE ) out[x %like_case% "strep[a-z]* group [abcdefghijkl]$"] <- gsub(".* ([abcdefghijkl])$", "B_STRPT_GRP\\U\\1", x[x %like_case% "strep[a-z]* group [abcdefghijkl]$"], perl = TRUE ) out[x %like_case% "group [abcdefghijkl] strepto[ck]o[ck]"] <- gsub(".*group ([abcdefghijkl]) strepto[ck]o[ck].*", "B_STRPT_GRP\\U\\1", x[x %like_case% "group [abcdefghijkl] strepto[ck]o[ck]"], perl = TRUE ) out[x %like_case% "ha?emoly.*strep"] <- "B_STRPT_HAEM" out[x %like_case% "(strepto.* [abcg, ]{2,4}$)"] <- "B_STRPT_ABCG" out[x %like_case% "(strepto.* mil+er+i|^mgs[^a-z]*$)"] <- "B_STRPT_MILL" out[x %like_case% "mil+er+i gr"] <- "B_STRPT_MILL" out[x %like_case% "((strepto|^s).* viridans|^vgs[^a-z]*$)"] <- "B_STRPT_VIRI" out[x %like_case% "(viridans.* (strepto|^s).*|^vgs[^a-z]*$)"] <- "B_STRPT_VIRI" # Salmonella in different languages, like "Salmonella grupo B" out[x %like_case% "salmonella.* [abcdefgh]$"] <- gsub(".*salmonella.* ([abcdefgh])$", "B_SLMNL_GRP\\U\\1", x[x %like_case% "salmonella.* [abcdefgh]$"], perl = TRUE ) out[x %like_case% "group [abcdefgh] salmonella"] <- gsub(".*group ([abcdefgh]) salmonella*", "B_SLMNL_GRP\\U\\1", x[x %like_case% "group [abcdefgh] salmonella"], perl = TRUE ) # CoNS/CoPS in different languages (support for German, Dutch, Spanish, Portuguese) out[x %like_case% "([ck]oagulas[ea].negatie?[vf]|^[ck]o?ns[^a-z]*$)"] <- "B_STPHY_CONS" out[x %like_case% "([ck]oagulas[ea].positie?[vf]|^[ck]o?ps[^a-z]*$)"] <- "B_STPHY_COPS" # Gram stains out[x %like_case% "gram[ -]?neg.*"] <- "B_GRAMN" out[x %like_case% "( |^)gram[-]( |$)"] <- "B_GRAMN" out[x %like_case% "gram[ -]?pos.*"] <- "B_GRAMP" out[x %like_case% "( |^)gram[+]( |$)"] <- "B_GRAMP" out[x %like_case% "anaerob[a-z]+ .*gram[ -]?neg.*"] <- "B_ANAER-NEG" out[x %like_case% "anaerob[a-z]+ .*gram[ -]?pos.*"] <- "B_ANAER-POS" out[is.na(out) & x %like_case% "anaerob[a-z]+ (micro)?.*organism"] <- "B_ANAER" # coryneform bacteria out[x %like_case% "^coryneform"] <- "B_CORYNF" # yeasts and fungi out[x %like_case% "^yeast?"] <- "F_YEAST" out[x %like_case% "^fung(us|i)"] <- "F_FUNGUS" # trivial names known to the field out[x %like_case% "meningo[ck]o[ck]"] <- "B_NESSR_MNNG" out[x %like_case% "gono[ck]o[ck]"] <- "B_NESSR_GNRR" out[x %like_case% "pneumo[ck]o[ck]"] <- "B_STRPT_PNMN" out[x %like_case% "hacek"] <- "B_HACEK" out[x %like_case% "haemophilus" & x %like_case% "aggregatibacter" & x %like_case% "cardiobacterium" & x %like_case% "eikenella" & x %like_case% "kingella"] <- "B_HACEK" out[x %like_case% "slow.* grow.* mycobact"] <- "B_MYCBC_SGM" out[x %like_case% "rapid.* grow.* mycobact"] <- "B_MYCBC_RGM" # unexisting names (con is the WHONET code for contamination) out[x %in% c("con", "other", "none", "unknown") | x %like_case% "virus"] <- "UNKNOWN" # WHONET has a lot of E. coli and Vibrio cholerae names out[x %like_case% "escherichia coli"] <- "B_ESCHR_COLI" out[x %like_case% "vibrio cholerae"] <- "B_VIBRI_CHLR" out } italicise <- function(x) { if (!has_colour()) { return(x) } out <- font_italic(x, collapse = NULL) # city-like serovars of Salmonella (start with a capital) out[x %like_case% "Salmonella [A-Z]"] <- paste( font_italic("Salmonella"), gsub("Salmonella ", "", x[x %like_case% "Salmonella [A-Z]"]) ) # streptococcal groups out[x %like_case% "Streptococcus [A-Z]"] <- paste( font_italic("Streptococcus"), gsub("Streptococcus ", "", x[x %like_case% "Streptococcus [A-Z]"]) ) # be sure not to make these italic out <- gsub("([ -]*)(Group|group|Complex|complex)(\033\\[23m)?", "\033[23m\\1\\2", out, perl = TRUE) out <- gsub("(\033\\[3m)?(Beta[-]haemolytic|Coagulase[-](postive|negative)) ", "\\2 \033[3m", out, perl = TRUE) out } nr2char <- function(x) { if (x %in% c(1:10)) { v <- c( "one" = 1, "two" = 2, "three" = 3, "four" = 4, "five" = 5, "six" = 6, "seven" = 7, "eight" = 8, "nine" = 9, "ten" = 10 ) names(v[x]) } else { x } } parse_and_convert <- function(x) { if (tryCatch(is.character(x) && all(Encoding(x) == "unknown", na.rm = TRUE), error = function(e) FALSE)) { out <- x } else { out <- tryCatch( { if (!is.null(dim(x))) { if (NCOL(x) > 2) { stop("a maximum of two columns is allowed", call. = FALSE) } else if (NCOL(x) == 2) { # support Tidyverse selection like: df %>% select(colA, colB) # paste these columns together x <- as.data.frame(x, stringsAsFactors = FALSE) colnames(x) <- c("A", "B") x <- paste(x$A, x$B) } else { # support Tidyverse selection like: df %>% select(colA) x <- as.data.frame(x, stringsAsFactors = FALSE)[[1]] } } parsed <- iconv(as.character(x), to = "UTF-8") parsed[is.na(parsed) & !is.na(x)] <- iconv(x[is.na(parsed) & !is.na(x)], from = "Latin1", to = "ASCII//TRANSLIT") parsed <- gsub('"', "", parsed, fixed = TRUE) parsed }, error = function(e) stop(e$message, call. = FALSE) ) # this will also be thrown when running `as.mo(no_existing_object)` } out <- trimws2(out) out <- gsub(" +", " ", out, perl = TRUE) out <- gsub(" ?/ ? ", "/", out, perl = TRUE) out } replace_old_mo_codes <- function(x, property) { # this function transform old MO codes to current codes, such as: # B_ESCH_COL (AMR v0.5.0) -> B_ESCHR_COLI ind <- x %like_case% "^[A-Z]_[A-Z_]+$" & !x %in% AMR_env$MO_lookup$mo if (any(ind, na.rm = TRUE)) { add_MO_lookup_to_AMR_env() # get the ones that match affected <- x[ind] affected_unique <- unique(affected) all_direct_matches <- TRUE # find their new codes, once per code solved_unique <- unlist(lapply( strsplit(affected_unique, ""), function(m) { kingdom <- paste0("^", m[1]) name <- m[3:length(m)] name[name == "_"] <- " " name <- tolower(paste0(name, ".*", collapse = "")) name <- gsub(" .*", " ", name, fixed = TRUE) name <- paste0("^", name) results <- AMR_env$MO_lookup$mo[AMR_env$MO_lookup$kingdom %like_case% kingdom & AMR_env$MO_lookup$fullname_lower %like_case% name] if (length(results) > 1) { all_direct_matches <<- FALSE } results[1L] } ), use.names = FALSE) solved <- solved_unique[match(affected, affected_unique)] # assign on places where a match was found x[ind] <- solved n_matched <- length(affected[!is.na(affected)]) n_solved <- length(affected[!is.na(solved)]) n_unsolved <- length(affected[is.na(solved)]) n_unique <- length(affected_unique[!is.na(affected_unique)]) if (n_unique < n_matched) { n_unique <- paste0(n_unique, " unique, ") } else { n_unique <- "" } if (property != "mo") { warning_( "in `mo_", property, "()`: the input contained ", n_matched, " old MO code", ifelse(n_matched == 1, "", "s"), " (", n_unique, "from a previous AMR package version). ", "Please update your MO codes with `as.mo()` to increase speed." ) } else { warning_( "in `as.mo()`: the input contained ", n_matched, " old MO code", ifelse(n_matched == 1, "", "s"), " (", n_unique, "from a previous AMR package version). ", n_solved, " old MO code", ifelse(n_solved == 1, "", "s"), ifelse(n_solved == 1, " was", " were"), ifelse(all_direct_matches, " updated ", font_bold(" guessed ")), "to ", ifelse(n_solved == 1, "a ", ""), "currently used MO code", ifelse(n_solved == 1, "", "s"), ifelse(n_unsolved > 0, paste0(" and ", n_unsolved, " old MO code", ifelse(n_unsolved == 1, "", "s"), " could not be updated."), "." ) ) } } x } replace_ignore_pattern <- function(x, ignore_pattern) { if (!is.null(ignore_pattern) && !identical(trimws2(ignore_pattern), "")) { ignore_cases <- x %like% ignore_pattern if (sum(ignore_cases) > 0) { message_( "The following input was ignored by `ignore_pattern = \"", ignore_pattern, "\"`: ", vector_and(x[ignore_cases], quotes = TRUE) ) x[ignore_cases] <- NA_character_ } } x } repair_reference_df <- function(reference_df) { if (is.null(reference_df)) { return(NULL) } # has valid own reference_df reference_df <- reference_df %pm>% pm_filter(!is.na(mo)) # keep only first two columns, second must be mo if (colnames(reference_df)[1] == "mo") { reference_df <- reference_df %pm>% pm_select(2, "mo") } else { reference_df <- reference_df %pm>% pm_select(1, "mo") } # remove factors, just keep characters colnames(reference_df)[1] <- "x" reference_df[, "x"] <- as.character(reference_df[, "x", drop = TRUE]) reference_df[, "mo"] <- as.character(reference_df[, "mo", drop = TRUE]) # some MO codes might be old reference_df[, "mo"] <- as.mo(reference_df[, "mo", drop = TRUE], reference_df = NULL) reference_df } get_mo_uncertainties <- function() { remember <- list(uncertainties = AMR_env$mo_uncertainties) # empty them, otherwise e.g. mo_shortname("Chlamydophila psittaci") will give 3 notes AMR_env$mo_uncertainties <- NULL remember } load_mo_uncertainties <- function(metadata) { AMR_env$mo_uncertainties <- metadata$uncertainties } synonym_mo_to_accepted_mo <- function(x, fill_in_accepted = FALSE) { x_gbif <- AMR_env$MO_lookup$gbif_renamed_to[match(x, AMR_env$MO_lookup$mo)] x_lpsn <- AMR_env$MO_lookup$lpsn_renamed_to[match(x, AMR_env$MO_lookup$mo)] x_gbif[!x_gbif %in% AMR_env$MO_lookup$gbif] <- NA x_lpsn[!x_lpsn %in% AMR_env$MO_lookup$lpsn] <- NA out <- ifelse(is.na(x_lpsn), AMR_env$MO_lookup$mo[match(x_gbif, AMR_env$MO_lookup$gbif)], AMR_env$MO_lookup$mo[match(x_lpsn, AMR_env$MO_lookup$lpsn)] ) if (isTRUE(fill_in_accepted)) { x_accepted <- which(AMR_env$MO_lookup$status[match(x, AMR_env$MO_lookup$mo)] == "accepted") out[x_accepted] <- x[x_accepted] } out }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mo.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Calculate the Matching Score for Microorganisms #' #' This algorithm is used by [as.mo()] and all the [`mo_*`][mo_property()] functions to determine the most probable match of taxonomic records based on user input. #' @author Dr. Matthijs Berends, 2018 #' @param x Any user input value(s) #' @param n A full taxonomic name, that exists in [`microorganisms$fullname`][microorganisms] #' @note This algorithm was originally described in: Berends MS *et al.* (2022). **AMR: An R Package for Working with Antimicrobial Resistance Data**. *Journal of Statistical Software*, 104(3), 1-31; \doi{10.18637/jss.v104.i03}. #' #' Later, the work of Bartlett A *et al.* about bacterial pathogens infecting humans (2022, \doi{10.1099/mic.0.001269}) was incorporated. #' @section Matching Score for Microorganisms: #' With ambiguous user input in [as.mo()] and all the [`mo_*`][mo_property()] functions, the returned results are chosen based on their matching score using [mo_matching_score()]. This matching score \eqn{m}, is calculated as: #' #' \ifelse{latex}{\deqn{m_{(x, n)} = \frac{l_{n} - 0.5 \cdot \min \begin{cases}l_{n} \\ \textrm{lev}(x, n)\end{cases}}{l_{n} \cdot p_{n} \cdot k_{n}}}}{ #' #' \ifelse{html}{\figure{mo_matching_score.png}{options: width="300" alt="mo matching score"}}{m(x, n) = ( l_n * min(l_n, lev(x, n) ) ) / ( l_n * p_n * k_n )}} #' #' where: #' #' * \eqn{x} is the user input; #' * \eqn{n} is a taxonomic name (genus, species, and subspecies); #' * \eqn{l_n} is the length of \eqn{n}; #' * \eqn{lev} is the [Levenshtein distance function](https://en.wikipedia.org/wiki/Levenshtein_distance) (counting any insertion as 1, and any deletion or substitution as 2) that is needed to change \eqn{x} into \eqn{n}; #' * \eqn{p_n} is the human pathogenic prevalence group of \eqn{n}, as described below; #' * \eqn{k_n} is the taxonomic kingdom of \eqn{n}, set as Bacteria = 1, Fungi = 1.25, Protozoa = 1.5, Archaea = 2, others = 3. #' #' The grouping into human pathogenic prevalence \eqn{p} is based on recent work from Bartlett *et al.* (2022, \doi{10.1099/mic.0.001269}) who extensively studied medical-scientific literature to categorise all bacterial species into these groups: #' #' - **Established**, if a taxonomic species has infected at least three persons in three or more references. These records have `prevalence = 1.0` in the [microorganisms] data set; #' - **Putative**, if a taxonomic species has fewer than three known cases. These records have `prevalence = 1.25` in the [microorganisms] data set. #' #' Furthermore, #' #' - Any genus present in the **established** list also has `prevalence = 1.0` in the [microorganisms] data set; #' - Any other genus present in the **putative** list has `prevalence = 1.25` in the [microorganisms] data set; #' - Any other species or subspecies of which the genus is present in the two aforementioned groups, has `prevalence = 1.5` in the [microorganisms] data set; #' - Any *non-bacterial* genus, species or subspecies of which the genus is present in the following list, has `prevalence = 1.25` in the [microorganisms] data set: `r vector_or(MO_PREVALENT_GENERA, quotes = "*")`; #' - All other records have `prevalence = 2.0` in the [microorganisms] data set. #' #' When calculating the matching score, all characters in \eqn{x} and \eqn{n} are ignored that are other than A-Z, a-z, 0-9, spaces and parentheses. #' #' All matches are sorted descending on their matching score and for all user input values, the top match will be returned. This will lead to the effect that e.g., `"E. coli"` will return the microbial ID of *Escherichia coli* (\eqn{m = `r round(mo_matching_score("E. coli", "Escherichia coli"), 3)`}, a highly prevalent microorganism found in humans) and not *Entamoeba coli* (\eqn{m = `r round(mo_matching_score("E. coli", "Entamoeba coli"), 3)`}, a less prevalent microorganism in humans), although the latter would alphabetically come first. #' @export #' @inheritSection AMR Reference Data Publicly Available #' @examples #' mo_reset_session() #' #' as.mo("E. coli") #' mo_uncertainties() #' #' mo_matching_score( #' x = "E. coli", #' n = c("Escherichia coli", "Entamoeba coli") #' ) mo_matching_score <- function(x, n) { meet_criteria(x, allow_class = c("character", "data.frame", "list")) meet_criteria(n, allow_class = "character") add_MO_lookup_to_AMR_env() x <- parse_and_convert(x) # no dots and other non-whitespace characters x <- gsub("[^a-zA-Z0-9 \\(\\)]+", "", x) # only keep one space x <- gsub(" +", " ", x) # force a capital letter, so this conversion will not count as a substitution substr(x, 1, 1) <- toupper(substr(x, 1, 1)) # n is always a taxonomically valid full name if (length(n) == 1) { n <- rep(n, length(x)) } if (length(x) == 1) { x <- rep(x, length(n)) } # length of fullname l_n <- nchar(n) lev <- double(length = length(x)) l_n.lev <- double(length = length(x)) # get Levenshtein distance lev <- unlist(Map(f = function(a, b) { as.double(utils::adist(a, b, ignore.case = FALSE, fixed = TRUE, costs = c(insertions = 1, deletions = 2, substitutions = 2), counts = FALSE )) }, x, n, USE.NAMES = FALSE)) l_n.lev[l_n < lev] <- l_n[l_n < lev] l_n.lev[lev < l_n] <- lev[lev < l_n] l_n.lev[lev == l_n] <- lev[lev == l_n] # human pathogenic prevalence (1 to 3), see ?as.mo p_n <- AMR_env$MO_lookup[match(n, AMR_env$MO_lookup$fullname), "prevalence", drop = TRUE] # kingdom index (Bacteria = 1, Fungi = 2, Protozoa = 3, Archaea = 4, others = 5) k_n <- AMR_env$MO_lookup[match(n, AMR_env$MO_lookup$fullname), "kingdom_index", drop = TRUE] # matching score: (l_n - 0.5 * l_n.lev) / (l_n * p_n * k_n) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mo_matching_score.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Get Properties of a Microorganism #' #' Use these functions to return a specific property of a microorganism based on the latest accepted taxonomy. All input values will be evaluated internally with [as.mo()], which makes it possible to use microbial abbreviations, codes and names as input. See *Examples*. #' @param x any [character] (vector) that can be coerced to a valid microorganism code with [as.mo()]. Can be left blank for auto-guessing the column containing microorganism codes if used in a data set, see *Examples*. #' @param property one of the column names of the [microorganisms] data set: `r vector_or(colnames(microorganisms), sort = FALSE, quotes = TRUE)`, or must be `"shortname"` #' @inheritParams as.mo #' @param ... other arguments passed on to [as.mo()], such as 'minimum_matching_score', 'ignore_pattern', and 'remove_from_input' #' @param ab any (vector of) text that can be coerced to a valid antibiotic drug code with [as.ab()] #' @param open browse the URL using [`browseURL()`][utils::browseURL()] #' @details All functions will, at default, **not** keep old taxonomic properties, as synonyms are automatically replaced with the current taxonomy. Take for example *Enterobacter aerogenes*, which was initially named in 1960 but renamed to *Klebsiella aerogenes* in 2017: #' - `mo_genus("Enterobacter aerogenes")` will return `"Klebsiella"` (with a note about the renaming) #' - `mo_genus("Enterobacter aerogenes", keep_synonyms = TRUE)` will return `"Enterobacter"` (with a once-per-session warning that the name is outdated) #' - `mo_ref("Enterobacter aerogenes")` will return `"Tindall et al., 2017"` (with a note) #' - `mo_ref("Enterobacter aerogenes", keep_synonyms = TRUE)` will return `"Hormaeche et al., 1960"` (with a warning) #' #' The short name ([mo_shortname()]) returns the first character of the genus and the full species, such as `"E. coli"`, for species and subspecies. Exceptions are abbreviations of staphylococci (such as *"CoNS"*, Coagulase-Negative Staphylococci) and beta-haemolytic streptococci (such as *"GBS"*, Group B Streptococci). Please bear in mind that e.g. *E. coli* could mean *Escherichia coli* (kingdom of Bacteria) as well as *Entamoeba coli* (kingdom of Protozoa). Returning to the full name will be done using [as.mo()] internally, giving priority to bacteria and human pathogens, i.e. `"E. coli"` will be considered *Escherichia coli*. As a result, `mo_fullname(mo_shortname("Entamoeba coli"))` returns `"Escherichia coli"`. #' #' Since the top-level of the taxonomy is sometimes referred to as 'kingdom' and sometimes as 'domain', the functions [mo_kingdom()] and [mo_domain()] return the exact same results. #' #' Determination of human pathogenicity ([mo_pathogenicity()]) is strongly based on Bartlett *et al.* (2022, \doi{10.1099/mic.0.001269}). This function returns a [factor] with the levels *Pathogenic*, *Potentially pathogenic*, *Non-pathogenic*, and *Unknown*. #' #' Determination of the Gram stain ([mo_gramstain()]) will be based on the taxonomic kingdom and phylum. Originally, Cavalier-Smith defined the so-called subkingdoms Negibacteria and Posibacteria (2002, [PMID 11837318](https://pubmed.ncbi.nlm.nih.gov/11837318/)), and only considered these phyla as Posibacteria: Actinobacteria, Chloroflexi, Firmicutes, and Tenericutes. These phyla were later renamed to Actinomycetota, Chloroflexota, Bacillota, and Mycoplasmatota (2021, [PMID 34694987](https://pubmed.ncbi.nlm.nih.gov/34694987/)). Bacteria in these phyla are considered Gram-positive in this `AMR` package, except for members of the class Negativicutes (within phylum Bacillota) which are Gram-negative. All other bacteria are considered Gram-negative. Species outside the kingdom of Bacteria will return a value `NA`. Functions [mo_is_gram_negative()] and [mo_is_gram_positive()] always return `TRUE` or `FALSE` (or `NA` when the input is `NA` or the MO code is `UNKNOWN`), thus always return `FALSE` for species outside the taxonomic kingdom of Bacteria. #' #' Determination of yeasts ([mo_is_yeast()]) will be based on the taxonomic kingdom and class. *Budding yeasts* are fungi of the phylum Ascomycota, class Saccharomycetes (also called Hemiascomycetes). *True yeasts* are aggregated into the underlying order Saccharomycetales. Thus, for all microorganisms that are member of the taxonomic class Saccharomycetes, the function will return `TRUE`. It returns `FALSE` otherwise (or `NA` when the input is `NA` or the MO code is `UNKNOWN`). #' #' Determination of intrinsic resistance ([mo_is_intrinsic_resistant()]) will be based on the [intrinsic_resistant] data set, which is based on `r format_eucast_version_nr(3.3)`. The [mo_is_intrinsic_resistant()] function can be vectorised over both argument `x` (input for microorganisms) and `ab` (input for antibiotics). #' #' Determination of bacterial oxygen tolerance ([mo_oxygen_tolerance()]) will be based on BacDive, see *Source*. The function [mo_is_anaerobic()] only returns `TRUE` if the oxygen tolerance is `"anaerobe"`, indicting an obligate anaerobic species or genus. It always returns `FALSE` for species outside the taxonomic kingdom of Bacteria. #' #' The function [mo_url()] will return the direct URL to the online database entry, which also shows the scientific reference of the concerned species. #' #' SNOMED codes ([mo_snomed()]) are from the version of `r documentation_date(TAXONOMY_VERSION$SNOMED$accessed_date)`. See *Source* and the [microorganisms] data set for more info. #' #' Old taxonomic names (so-called 'synonyms') can be retrieved with [mo_synonyms()] (which will have the scientific reference as [name][base::names()]), the current taxonomic name can be retrieved with [mo_current()]. Both functions return full names. #' #' All output [will be translated][translate] where possible. #' @section Matching Score for Microorganisms: #' This function uses [as.mo()] internally, which uses an advanced algorithm to translate arbitrary user input to valid taxonomy using a so-called matching score. You can read about this public algorithm on the [MO matching score page][mo_matching_score()]. #' @inheritSection as.mo Source #' @rdname mo_property #' @name mo_property #' @return #' - An [integer] in case of [mo_year()] #' - An [ordered factor][factor] in case of [mo_pathogenicity()] #' - A [list] in case of [mo_taxonomy()], [mo_synonyms()], [mo_snomed()] and [mo_info()] #' - A named [character] in case of [mo_url()] #' - A [character] in all other cases #' @export #' @seealso Data set [microorganisms] #' @inheritSection AMR Reference Data Publicly Available #' @examples #' # taxonomic tree ----------------------------------------------------------- #' #' mo_kingdom("Klebsiella pneumoniae") #' mo_phylum("Klebsiella pneumoniae") #' mo_class("Klebsiella pneumoniae") #' mo_order("Klebsiella pneumoniae") #' mo_family("Klebsiella pneumoniae") #' mo_genus("Klebsiella pneumoniae") #' mo_species("Klebsiella pneumoniae") #' mo_subspecies("Klebsiella pneumoniae") #' #' #' # full names and short names ----------------------------------------------- #' #' mo_name("Klebsiella pneumoniae") #' mo_fullname("Klebsiella pneumoniae") #' mo_shortname("Klebsiella pneumoniae") #' #' #' # other properties --------------------------------------------------------- #' #' mo_pathogenicity("Klebsiella pneumoniae") #' mo_gramstain("Klebsiella pneumoniae") #' mo_snomed("Klebsiella pneumoniae") #' mo_type("Klebsiella pneumoniae") #' mo_rank("Klebsiella pneumoniae") #' mo_url("Klebsiella pneumoniae") #' mo_is_yeast(c("Candida", "Trichophyton", "Klebsiella")) #' #' #' # scientific reference ----------------------------------------------------- #' #' mo_ref("Klebsiella aerogenes") #' mo_authors("Klebsiella aerogenes") #' mo_year("Klebsiella aerogenes") #' mo_lpsn("Klebsiella aerogenes") #' mo_gbif("Klebsiella aerogenes") #' mo_synonyms("Klebsiella aerogenes") #' #' #' # abbreviations known in the field ----------------------------------------- #' #' mo_genus("MRSA") #' mo_species("MRSA") #' mo_shortname("VISA") #' mo_gramstain("VISA") #' #' mo_genus("EHEC") #' mo_species("EIEC") #' mo_name("UPEC") #' #' #' # known subspecies --------------------------------------------------------- #' #' mo_fullname("K. pneu rh") #' mo_shortname("K. pneu rh") #' #' \donttest{ #' # Becker classification, see ?as.mo ---------------------------------------- #' #' mo_fullname("Staph epidermidis") #' mo_fullname("Staph epidermidis", Becker = TRUE) #' mo_shortname("Staph epidermidis") #' mo_shortname("Staph epidermidis", Becker = TRUE) #' #' #' # Lancefield classification, see ?as.mo ------------------------------------ #' #' mo_fullname("Strep agalactiae") #' mo_fullname("Strep agalactiae", Lancefield = TRUE) #' mo_shortname("Strep agalactiae") #' mo_shortname("Strep agalactiae", Lancefield = TRUE) #' #' #' # language support -------------------------------------------------------- #' #' mo_gramstain("Klebsiella pneumoniae", language = "de") # German #' mo_gramstain("Klebsiella pneumoniae", language = "nl") # Dutch #' mo_gramstain("Klebsiella pneumoniae", language = "es") # Spanish #' mo_gramstain("Klebsiella pneumoniae", language = "el") # Greek #' mo_gramstain("Klebsiella pneumoniae", language = "uk") # Ukrainian #' #' # mo_type is equal to mo_kingdom, but mo_kingdom will remain untranslated #' mo_kingdom("Klebsiella pneumoniae") #' mo_type("Klebsiella pneumoniae") #' mo_kingdom("Klebsiella pneumoniae", language = "zh") # Chinese, no effect #' mo_type("Klebsiella pneumoniae", language = "zh") # Chinese, translated #' #' mo_fullname("S. pyogenes", Lancefield = TRUE, language = "de") #' mo_fullname("S. pyogenes", Lancefield = TRUE, language = "uk") #' #' #' # other -------------------------------------------------------------------- #' #' # gram stains and intrinsic resistance can be used as a filter in dplyr verbs #' if (require("dplyr")) { #' example_isolates %>% #' filter(mo_is_gram_positive()) %>% #' count(mo_genus(), sort = TRUE) #' } #' if (require("dplyr")) { #' example_isolates %>% #' filter(mo_is_intrinsic_resistant(ab = "vanco")) %>% #' count(mo_genus(), sort = TRUE) #' } #' #' # get a list with the complete taxonomy (from kingdom to subspecies) #' mo_taxonomy("Klebsiella pneumoniae") #' #' # get a list with the taxonomy, the authors, Gram-stain, #' # SNOMED codes, and URL to the online database #' mo_info("Klebsiella pneumoniae") #' } mo_name <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_name") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "fullname", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = FALSE, only_affect_mo_names = TRUE ) } #' @rdname mo_property #' @export mo_fullname <- mo_name #' @rdname mo_property #' @export mo_shortname <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_shortname") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() replace_empty <- function(x) { x[x == ""] <- "spp." x } # get first char of genus and complete species in English genera <- mo_genus(x.mo, language = NULL, keep_synonyms = keep_synonyms) shortnames <- paste0(substr(genera, 1, 1), ". ", replace_empty(mo_species(x.mo, language = NULL, keep_synonyms = keep_synonyms))) # exceptions for where no species is known shortnames[shortnames %like% ".[.] spp[.]"] <- genera[shortnames %like% ".[.] spp[.]"] # exceptions for staphylococci shortnames[shortnames == "S. coagulase-negative"] <- "CoNS" shortnames[shortnames == "S. coagulase-positive"] <- "CoPS" # exceptions for streptococci: Group A Streptococcus -> GAS shortnames[shortnames %like_case% "S. Group [ABCDFGHK]"] <- paste0("G", gsub("S. Group ([ABCDFGHK])", "\\1", shortnames[shortnames %like_case% "S. Group [ABCDFGHK]"], perl = TRUE), "S") # unknown species etc. shortnames[shortnames %like% "unknown"] <- paste0("(", trimws2(gsub("[^a-zA-Z -]", "", shortnames[shortnames %like% "unknown"], perl = TRUE)), ")") shortnames[mo_rank(x.mo) %in% c("kingdom", "phylum", "class", "order", "family")] <- mo_name(x.mo, language = NULL, keep_synonyms = keep_synonyms) shortnames[is.na(x.mo)] <- NA_character_ load_mo_uncertainties(metadata) translate_into_language(shortnames, language = language, only_unknown = FALSE, only_affect_mo_names = TRUE) } #' @rdname mo_property #' @export mo_subspecies <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_subspecies") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "subspecies", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_species <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_species") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "species", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_genus <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_genus") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "genus", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_family <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_family") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "family", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_order <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_order") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "order", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_class <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_class") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "class", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_phylum <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_phylum") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "phylum", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_kingdom <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_kingdom") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "kingdom", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_domain <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_domain") } mo_kingdom(x = x, language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_type <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_type") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) out <- mo_kingdom(x.mo, language = NULL, keep_synonyms = keep_synonyms) out[which(mo_is_yeast(x.mo, keep_synonyms = keep_synonyms))] <- "Yeasts" translate_into_language(out, language = language, only_unknown = FALSE) } #' @rdname mo_property #' @export mo_status <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_status") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = "status", language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } #' @rdname mo_property #' @export mo_pathogenicity <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_pathogenicity") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) add_MO_lookup_to_AMR_env() x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() prev <- AMR_env$MO_lookup$prevalence[match(x.mo, AMR_env$MO_lookup$mo)] kngd <- AMR_env$MO_lookup$kingdom[match(x.mo, AMR_env$MO_lookup$mo)] rank <- AMR_env$MO_lookup$rank[match(x.mo, AMR_env$MO_lookup$mo)] out <- factor(case_when_AMR(prev == 1 & kngd == "Bacteria" & rank != "genus" ~ "Pathogenic", (prev < 2 & kngd == "Fungi") ~ "Potentially pathogenic", prev == 2 & kngd == "Bacteria" ~ "Non-pathogenic", kngd == "Bacteria" ~ "Potentially pathogenic", TRUE ~ "Unknown"), levels = c("Pathogenic", "Potentially pathogenic", "Non-pathogenic", "Unknown"), ordered = TRUE ) load_mo_uncertainties(metadata) out } #' @rdname mo_property #' @export mo_gramstain <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_gramstain") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() x <- rep(NA_character_, length(x)) # make all bacteria Gram negative x[mo_kingdom(x.mo, language = NULL, keep_synonyms = keep_synonyms) == "Bacteria"] <- "Gram-negative" # overwrite these 4 phyla with Gram-positives # Source: https://itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value=956097 (Cavalier-Smith, 2002) x[(mo_phylum(x.mo, language = NULL, keep_synonyms = keep_synonyms) %in% c( # no longer in use, does not hurt to keep here: "Actinobacteria", "Chloroflexi", "Firmicutes", "Tenericutes", "Actinomycetota", # since 2021, old name was Actinobacteria "Chloroflexota", # since 2021, old name was Chloroflexi "Bacillota", # since 2021, old name was Firmicutes "Mycoplasmatota" # since 2021, old name was Tenericutes ) & # but class Negativicutes (of phylum Bacillota) are Gram-negative! mo_class(x.mo, language = NULL, keep_synonyms = keep_synonyms) != "Negativicutes") # and of course our own ID for Gram-positives | x.mo %in% c("B_GRAMP", "B_ANAER-POS")] <- "Gram-positive" load_mo_uncertainties(metadata) translate_into_language(x, language = language, only_unknown = FALSE) } #' @rdname mo_property #' @export mo_is_gram_negative <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_is_gram_negative") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() grams <- mo_gramstain(x.mo, language = NULL, keep_synonyms = keep_synonyms) load_mo_uncertainties(metadata) out <- grams == "Gram-negative" & !is.na(grams) out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA out } #' @rdname mo_property #' @export mo_is_gram_positive <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_is_gram_positive") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() grams <- mo_gramstain(x.mo, language = NULL, keep_synonyms = keep_synonyms) load_mo_uncertainties(metadata) out <- grams == "Gram-positive" & !is.na(grams) out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA out } #' @rdname mo_property #' @export mo_is_yeast <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_is_yeast") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() x.kingdom <- mo_kingdom(x.mo, language = NULL, keep_synonyms = keep_synonyms) x.class <- mo_class(x.mo, language = NULL, keep_synonyms = keep_synonyms) load_mo_uncertainties(metadata) out <- rep(FALSE, length(x)) out[x.kingdom == "Fungi" & x.class == "Saccharomycetes"] <- TRUE out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA out } #' @rdname mo_property #' @export mo_is_intrinsic_resistant <- function(x, ab, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_is_intrinsic_resistant") } meet_criteria(x, allow_NA = TRUE) meet_criteria(ab, allow_NA = FALSE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) ab <- as.ab(ab, language = NULL, flag_multiple_results = FALSE, info = FALSE) if (length(x) == 1 & length(ab) > 1) { x <- rep(x, length(ab)) } else if (length(ab) == 1 & length(x) > 1) { ab <- rep(ab, length(x)) } if (length(x) != length(ab)) { stop_("length of `x` and `ab` must be equal, or one of them must be of length 1.") } # show used version number once per session (AMR_env will reload every session) if (message_not_thrown_before("mo_is_intrinsic_resistant", "version.mo", entire_session = TRUE)) { message_( "Determining intrinsic resistance based on ", format_eucast_version_nr(3.3, markdown = FALSE), ". ", font_red("This note will be shown once per session.") ) } # runs against internal vector: intrinsic_resistant (see zzz.R) add_intrinsic_resistance_to_AMR_env() paste(x, ab) %in% AMR_env$intrinsic_resistant } #' @rdname mo_property #' @export mo_oxygen_tolerance <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_oxygen_tolerance") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "oxygen_tolerance", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_is_anaerobic <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_is_anaerobic") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() oxygen <- mo_oxygen_tolerance(x.mo, language = NULL, keep_synonyms = keep_synonyms) load_mo_uncertainties(metadata) out <- oxygen == "anaerobe" & !is.na(oxygen) out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA out } #' @rdname mo_property #' @export mo_snomed <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_snomed") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "snomed", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_ref <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_ref") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "ref", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_authors <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_authors") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x <- mo_validate(x = x, property = "ref", language = language, keep_synonyms = keep_synonyms, ...) # remove last 4 digits and presumably the comma and space that preceed them x[!is.na(x)] <- gsub(",? ?[0-9]{4}", "", x[!is.na(x)], perl = TRUE) suppressWarnings(x) } #' @rdname mo_property #' @export mo_year <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_year") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x <- mo_validate(x = x, property = "ref", language = language, keep_synonyms = keep_synonyms, ...) # get last 4 digits x[!is.na(x)] <- gsub(".*([0-9]{4})$", "\\1", x[!is.na(x)], perl = TRUE) suppressWarnings(as.integer(x)) } #' @rdname mo_property #' @export mo_lpsn <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_lpsn") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "lpsn", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_gbif <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_gbif") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "gbif", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_rank <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_rank") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) mo_validate(x = x, property = "rank", language = language, keep_synonyms = keep_synonyms, ...) } #' @rdname mo_property #' @export mo_taxonomy <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_taxonomy") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() out <- list( kingdom = mo_kingdom(x, language = language, keep_synonyms = keep_synonyms), phylum = mo_phylum(x, language = language, keep_synonyms = keep_synonyms), class = mo_class(x, language = language, keep_synonyms = keep_synonyms), order = mo_order(x, language = language, keep_synonyms = keep_synonyms), family = mo_family(x, language = language, keep_synonyms = keep_synonyms), genus = mo_genus(x, language = language, keep_synonyms = keep_synonyms), species = mo_species(x, language = language, keep_synonyms = keep_synonyms), subspecies = mo_subspecies(x, language = language, keep_synonyms = keep_synonyms) ) load_mo_uncertainties(metadata) out } #' @rdname mo_property #' @export mo_synonyms <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_synonyms") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) add_MO_lookup_to_AMR_env() x.mo <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() syns <- lapply(x.mo, function(y) { gbif <- AMR_env$MO_lookup$gbif[match(y, AMR_env$MO_lookup$mo)] lpsn <- AMR_env$MO_lookup$lpsn[match(y, AMR_env$MO_lookup$mo)] fullname <- AMR_env$MO_lookup[which(AMR_env$MO_lookup$lpsn_renamed_to == lpsn | AMR_env$MO_lookup$gbif_renamed_to == gbif), "fullname", drop = TRUE] if (length(fullname) == 0) { NULL } else { ref <- AMR_env$MO_lookup[which(AMR_env$MO_lookup$lpsn_renamed_to == lpsn | AMR_env$MO_lookup$gbif_renamed_to == gbif), "ref", drop = TRUE] names(fullname) <- ref fullname } }) if (length(syns) == 1) { syns <- unlist(syns) } load_mo_uncertainties(metadata) syns } #' @rdname mo_property #' @export mo_current <- function(x, language = get_AMR_locale(), ...) { meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) x.mo <- suppressWarnings(as.mo(x, keep_synonyms = TRUE, ...)) out <- synonym_mo_to_accepted_mo(x.mo, fill_in_accepted = TRUE) mo_name(out, language = language) } #' @rdname mo_property #' @export mo_info <- function(x, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_info") } meet_criteria(x, allow_NA = TRUE) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) x <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) metadata <- get_mo_uncertainties() info <- lapply(x, function(y) { c( list(mo = as.character(x)), mo_taxonomy(y, language = language, keep_synonyms = keep_synonyms), list( status = mo_status(y, language = language, keep_synonyms = keep_synonyms), synonyms = mo_synonyms(y, keep_synonyms = keep_synonyms), gramstain = mo_gramstain(y, language = language, keep_synonyms = keep_synonyms), oxygen_tolerance = mo_oxygen_tolerance(y, language = language, keep_synonyms = keep_synonyms), url = unname(mo_url(y, open = FALSE, keep_synonyms = keep_synonyms)), ref = mo_ref(y, keep_synonyms = keep_synonyms), snomed = unlist(mo_snomed(y, keep_synonyms = keep_synonyms)), lpsn = mo_lpsn(y, language = language, keep_synonyms = keep_synonyms), gbif = mo_gbif(y, language = language, keep_synonyms = keep_synonyms) ) ) }) if (length(info) > 1) { names(info) <- mo_name(x) result <- info } else { result <- info[[1L]] } load_mo_uncertainties(metadata) result } #' @rdname mo_property #' @export mo_url <- function(x, open = FALSE, language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_url") } meet_criteria(x, allow_NA = TRUE) meet_criteria(open, allow_class = "logical", has_length = 1) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) add_MO_lookup_to_AMR_env() x.mo <- as.mo(x = x, language = language, keep_synonyms = keep_synonyms, ... = ...) metadata <- get_mo_uncertainties() x.rank <- AMR_env$MO_lookup$rank[match(x.mo, AMR_env$MO_lookup$mo)] x.name <- AMR_env$MO_lookup$fullname[match(x.mo, AMR_env$MO_lookup$mo)] x.lpsn <- AMR_env$MO_lookup$lpsn[match(x.mo, AMR_env$MO_lookup$mo)] x.gbif <- AMR_env$MO_lookup$gbif[match(x.mo, AMR_env$MO_lookup$mo)] u <- character(length(x)) u[!is.na(x.gbif)] <- paste0(TAXONOMY_VERSION$GBIF$url, "/species/", x.gbif[!is.na(x.gbif)]) # overwrite with LPSN: u[!is.na(x.lpsn)] <- paste0(TAXONOMY_VERSION$LPSN$url, "/", x.rank[!is.na(x.lpsn)], "/", gsub(" ", "-", tolower(x.name[!is.na(x.lpsn)]), fixed = TRUE)) names(u) <- x.name if (isTRUE(open)) { if (length(u) > 1) { warning_("in `mo_url()`: only the first URL will be opened, as `browseURL()` only suports one string.") } utils::browseURL(u[1L]) } load_mo_uncertainties(metadata) u } #' @rdname mo_property #' @export mo_property <- function(x, property = "fullname", language = get_AMR_locale(), keep_synonyms = getOption("AMR_keep_synonyms", FALSE), ...) { if (missing(x)) { # this tries to find the data and an 'mo' column x <- find_mo_col(fn = "mo_property") } meet_criteria(x, allow_NA = TRUE) meet_criteria(property, allow_class = "character", has_length = 1, is_in = colnames(AMR::microorganisms)) language <- validate_language(language) meet_criteria(keep_synonyms, allow_class = "logical", has_length = 1) translate_into_language(mo_validate(x = x, property = property, language = language, keep_synonyms = keep_synonyms, ...), language = language, only_unknown = TRUE) } mo_validate <- function(x, property, language, keep_synonyms = keep_synonyms, ...) { add_MO_lookup_to_AMR_env() # try to catch an error when inputting an invalid argument # so the 'call.' can be set to FALSE tryCatch(x[1L] %in% unlist(AMR_env$MO_lookup[1, property, drop = TRUE]), error = function(e) stop(e$message, call. = FALSE) ) dots <- list(...) Becker <- dots$Becker if (is.null(Becker) || property %in% c("kingdom", "phylum", "class", "order", "family", "genus")) { Becker <- FALSE } Lancefield <- dots$Lancefield if (is.null(Lancefield) || property %in% c("kingdom", "phylum", "class", "order", "family", "genus")) { Lancefield <- FALSE } has_Becker_or_Lancefield <- Becker %in% c(TRUE, "all") || Lancefield %in% c(TRUE, "all") if (isFALSE(has_Becker_or_Lancefield) && isTRUE(keep_synonyms) && all(x %in% c(AMR_env$MO_lookup$mo, NA))) { # fastest way to get properties if (property == "snomed") { x <- lapply(x, function(y) unlist(AMR_env$MO_lookup$snomed[match(y, AMR_env$MO_lookup$mo)])) } else { x <- AMR_env$MO_lookup[[property]][match(x, AMR_env$MO_lookup$mo)] } } else { # get microorganisms data set, but remove synonyms if keep_synonyms is FALSE mo_data_check <- AMR_env$MO_lookup[which(AMR_env$MO_lookup$status %in% if (isTRUE(keep_synonyms)) c("synonym", "accepted") else "accepted"), , drop = FALSE] if (all(x %in% c(mo_data_check$mo, NA)) && !has_Becker_or_Lancefield) { # do nothing, just don't run the other if-else's } else if (all(x %in% c(unlist(mo_data_check[[property]]), NA)) && !has_Becker_or_Lancefield) { # no need to do anything, just return it return(x) } else { # we need to get MO codes now x <- replace_old_mo_codes(x, property = property) x <- as.mo(x, language = language, keep_synonyms = keep_synonyms, ...) } # get property reeaaally fast using match() if (property == "snomed") { x <- lapply(x, function(y) unlist(AMR_env$MO_lookup$snomed[match(y, AMR_env$MO_lookup$mo)])) } else { x <- AMR_env$MO_lookup[[property]][match(x, AMR_env$MO_lookup$mo)] } } if (property == "mo") { return(set_clean_class(x, new_class = c("mo", "character"))) } else if (property == "snomed") { return(x) } else if (property == "prevalence") { return(as.double(x)) } else { # everything else as character return(as.character(x)) } } find_mo_col <- function(fn) { # this function tries to find an mo column in the data the function was called in, # which is useful when functions are used within dplyr verbs df <- get_current_data(arg_name = "x", call = -3) # will return an error if not found mo <- NULL try( { mo <- suppressMessages(search_type_in_df(df, "mo")) }, silent = TRUE ) 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, "()`") } return(df[, mo, drop = TRUE]) } else { stop_("argument `x` is missing and no column with info about microorganisms could be found.", call = -2) } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mo_property.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' User-Defined Reference Data Set for Microorganisms #' #' @description These functions can be used to predefine your own reference to be used in [as.mo()] and consequently all [`mo_*`][mo_property()] functions (such as [mo_genus()] and [mo_gramstain()]). #' #' This is **the fastest way** to have your organisation (or analysis) specific codes picked up and translated by this package, since you don't have to bother about it again after setting it up once. #' @param path location of your reference file, this can be any text file (comma-, tab- or pipe-separated) or an Excel file (see *Details*). Can also be `""`, `NULL` or `FALSE` to delete the reference file. #' @param destination destination of the compressed data file - the default is the user's home directory. #' @rdname mo_source #' @name mo_source #' @aliases set_mo_source get_mo_source #' @details The reference file can be a text file separated with commas (CSV) or tabs or pipes, an Excel file (either 'xls' or 'xlsx' format) or an \R object file (extension '.rds'). To use an Excel file, you will need to have the `readxl` package installed. #' #' [set_mo_source()] will check the file for validity: it must be a [data.frame], must have a column named `"mo"` which contains values from [`microorganisms$mo`][microorganisms] or [`microorganisms$fullname`][microorganisms] and must have a reference column with your own defined values. If all tests pass, [set_mo_source()] will read the file into \R and will ask to export it to `"~/mo_source.rds"`. The CRAN policy disallows packages to write to the file system, although '*exceptions may be allowed in interactive sessions if the package obtains confirmation from the user*'. For this reason, this function only works in interactive sessions so that the user can **specifically confirm and allow** that this file will be created. The destination of this file can be set with the `destination` argument and defaults to the user's home directory. It can also be set with the [package option][AMR-options] [`AMR_mo_source`][AMR-options], e.g. `options(AMR_mo_source = "my/location/file.rds")`. #' #' The created compressed data file `"mo_source.rds"` will be used at default for MO determination (function [as.mo()] and consequently all `mo_*` functions like [mo_genus()] and [mo_gramstain()]). The location and timestamp of the original file will be saved as an [attribute][base::attributes()] to the compressed data file. #' #' The function [get_mo_source()] will return the data set by reading `"mo_source.rds"` with [readRDS()]. If the original file has changed (by checking the location and timestamp of the original file), it will call [set_mo_source()] to update the data file automatically if used in an interactive session. #' #' Reading an Excel file (`.xlsx`) with only one row has a size of 8-9 kB. The compressed file created with [set_mo_source()] will then have a size of 0.1 kB and can be read by [get_mo_source()] in only a couple of microseconds (millionths of a second). #' #' @section How to Setup: #' #' Imagine this data on a sheet of an Excel file. The first column contains the organisation specific codes, the second column contains valid taxonomic names: #' #' ``` #' | A | B | #' --|--------------------|-----------------------| #' 1 | Organisation XYZ | mo | #' 2 | lab_mo_ecoli | Escherichia coli | #' 3 | lab_mo_kpneumoniae | Klebsiella pneumoniae | #' 4 | | | #' ``` #' #' We save it as `"home/me/ourcodes.xlsx"`. Now we have to set it as a source: #' #' ``` #' set_mo_source("home/me/ourcodes.xlsx") #' #> NOTE: Created mo_source file '/Users/me/mo_source.rds' (0.3 kB) from #' #> '/Users/me/Documents/ourcodes.xlsx' (9 kB), columns #' #> "Organisation XYZ" and "mo" #' ``` #' #' It has now created a file `"~/mo_source.rds"` with the contents of our Excel file. Only the first column with foreign values and the 'mo' column will be kept when creating the RDS file. #' #' And now we can use it in our functions: #' #' ``` #' as.mo("lab_mo_ecoli") #' #> Class 'mo' #' #> [1] B_ESCHR_COLI #' #' mo_genus("lab_mo_kpneumoniae") #' #> [1] "Klebsiella" #' #' # other input values still work too #' as.mo(c("Escherichia coli", "E. coli", "lab_mo_ecoli")) #' #> NOTE: Translation to one microorganism was guessed with uncertainty. #' #> Use mo_uncertainties() to review it. #' #> Class 'mo' #' #> [1] B_ESCHR_COLI B_ESCHR_COLI B_ESCHR_COLI #' ``` #' #' If we edit the Excel file by, let's say, adding row 4 like this: #' #' ``` #' | A | B | #' --|--------------------|-----------------------| #' 1 | Organisation XYZ | mo | #' 2 | lab_mo_ecoli | Escherichia coli | #' 3 | lab_mo_kpneumoniae | Klebsiella pneumoniae | #' 4 | lab_Staph_aureus | Staphylococcus aureus | #' 5 | | | #' ``` #' #' ...any new usage of an MO function in this package will update your data file: #' #' ``` #' as.mo("lab_mo_ecoli") #' #> NOTE: Updated mo_source file '/Users/me/mo_source.rds' (0.3 kB) from #' #> '/Users/me/Documents/ourcodes.xlsx' (9 kB), columns #' #> "Organisation XYZ" and "mo" #' #> Class 'mo' #' #> [1] B_ESCHR_COLI #' #' mo_genus("lab_Staph_aureus") #' #> [1] "Staphylococcus" #' ``` #' #' To delete the reference data file, just use `""`, `NULL` or `FALSE` as input for [set_mo_source()]: #' #' ``` #' set_mo_source(NULL) #' #> Removed mo_source file '/Users/me/mo_source.rds' #' ``` #' #' If the original file (in the previous case an Excel file) is moved or deleted, the `mo_source.rds` file will be removed upon the next use of [as.mo()] or any [`mo_*`][mo_property()] function. #' @export set_mo_source <- function(path, destination = getOption("AMR_mo_source", "~/mo_source.rds")) { meet_criteria(path, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(destination, allow_class = "character", has_length = 1) stop_ifnot(destination %like% "[.]rds$", "the `destination` must be a file location with file extension .rds.") mo_source_destination <- path.expand(destination) stop_ifnot(interactive(), "this function can only be used in interactive mode, since it must ask for the user's permission to write a file to their file system.") if (is.null(path) || path %in% c(FALSE, "")) { AMR_env$mo_source <- NULL if (file.exists(mo_source_destination)) { unlink(mo_source_destination) message_("Removed mo_source file '", font_bold(mo_source_destination), "'", add_fn = font_red, as_note = FALSE ) } return(invisible()) } stop_ifnot(file.exists(path), "file not found: ", path) df <- NULL if (path %like% "[.]rds$") { df <- readRDS_AMR(path) } else if (path %like% "[.]xlsx?$") { # is Excel file (old or new) stop_ifnot_installed("readxl") df <- readxl::read_excel(path) } else if (path %like% "[.]tsv$") { df <- utils::read.table(file = path, header = TRUE, sep = "\t", stringsAsFactors = FALSE) } else if (path %like% "[.]csv$") { df <- utils::read.table(file = path, header = TRUE, sep = ",", stringsAsFactors = FALSE) } else { # try comma first try( df <- utils::read.table(file = path, header = TRUE, sep = ",", stringsAsFactors = FALSE), silent = TRUE ) if (!check_validity_mo_source(df, stop_on_error = FALSE)) { # try tab try( df <- utils::read.table(file = path, header = TRUE, sep = "\t", stringsAsFactors = FALSE), silent = TRUE ) } if (!check_validity_mo_source(df, stop_on_error = FALSE)) { # try pipe try( df <- utils::read.table(file = path, header = TRUE, sep = "|", stringsAsFactors = FALSE), silent = TRUE ) } } # check integrity if (is.null(df)) { stop_("the path '", path, "' could not be imported as a dataset.") } check_validity_mo_source(df) df <- subset(df, !is.na(mo)) # keep only first two columns, second must be mo if (colnames(df)[1] == "mo") { df <- df[, c(colnames(df)[2], "mo")] } else { df <- df[, c(colnames(df)[1], "mo")] } df <- as.data.frame(df, stringAsFactors = FALSE) df[, "mo"] <- as.mo(df[, "mo", drop = TRUE]) # success if (file.exists(mo_source_destination)) { action <- "Updated" } else { action <- "Created" # only ask when file is created, not when it is updated txt <- paste0( word_wrap(paste0( "This will write create the new file '", mo_source_destination, "', for which your permission is required." )), "\n\n", word_wrap("Do you agree that this file will be created?") ) showQuestion <- import_fn("showQuestion", "rstudioapi", error_on_fail = FALSE) if (!is.null(showQuestion)) { q_continue <- showQuestion("Create new file", txt) } else { q_continue <- utils::menu(choices = c("OK", "Cancel"), graphics = FALSE, title = txt) } if (q_continue %in% c(FALSE, 2)) { return(invisible()) } } attr(df, "mo_source_location") <- path attr(df, "mo_source_destination") <- mo_source_destination attr(df, "mo_source_timestamp") <- file.mtime(path) saveRDS(df, mo_source_destination) AMR_env$mo_source <- df message_( action, " mo_source file '", font_bold(mo_source_destination), "' (", formatted_filesize(mo_source_destination), ") from '", font_bold(path), "' (", formatted_filesize(path), '), columns "', colnames(df)[1], '" and "', colnames(df)[2], '"' ) } #' @rdname mo_source #' @export get_mo_source <- function(destination = getOption("AMR_mo_source", "~/mo_source.rds")) { if (!file.exists(path.expand(destination))) { if (interactive()) { # source file might have been deleted, so update reference set_mo_source("") } return(NULL) } if (is.null(AMR_env$mo_source)) { AMR_env$mo_source <- readRDS_AMR(path.expand(destination)) } old_time <- attributes(AMR_env$mo_source)$mo_source_timestamp new_time <- file.mtime(attributes(AMR_env$mo_source)$mo_source_location) if (interactive() && !identical(old_time, new_time)) { # source file was updated, also update reference set_mo_source(attributes(AMR_env$mo_source)$mo_source_location) } AMR_env$mo_source } check_validity_mo_source <- function(x, refer_to_name = "`reference_df`", stop_on_error = TRUE) { add_MO_lookup_to_AMR_env() if (paste(deparse(substitute(x)), collapse = "") == "get_mo_source()") { return(TRUE) } if (is.null(AMR_env$mo_source) && (identical(x, get_mo_source()))) { return(TRUE) } if (is.null(x)) { if (stop_on_error == TRUE) { stop_(refer_to_name, " cannot be NULL", call = FALSE) } else { return(FALSE) } } if (!is.data.frame(x)) { if (stop_on_error == TRUE) { stop_(refer_to_name, " must be a data.frame", call = FALSE) } else { return(FALSE) } } if (!"mo" %in% colnames(x)) { if (stop_on_error == TRUE) { stop_(refer_to_name, " must contain a column 'mo'", call = FALSE) } else { return(FALSE) } } if (!all(x$mo %in% c("", AMR_env$MO_lookup$mo, AMR_env$MO_lookup$fullname), na.rm = TRUE)) { if (stop_on_error == TRUE) { invalid <- x[which(!x$mo %in% c("", AMR_env$MO_lookup$mo, AMR_env$MO_lookup$fullname)), , drop = FALSE] if (nrow(invalid) > 1) { plural <- "s" } else { plural <- "" } stop_("Value", plural, " ", vector_and(invalid[, 1, drop = TRUE], quotes = TRUE), " found in ", tolower(refer_to_name), ", but with invalid microorganism code", plural, " ", vector_and(invalid$mo, quotes = TRUE), call = FALSE ) } else { return(FALSE) } } if (colnames(x)[1] != "mo" && nrow(x) > length(unique(x[, 1, drop = TRUE]))) { if (stop_on_error == TRUE) { stop_(refer_to_name, " contains duplicate values in column '", colnames(x)[1], "'", call = FALSE) } else { return(FALSE) } } if (colnames(x)[2] != "mo" && nrow(x) > length(unique(x[, 2, drop = TRUE]))) { if (stop_on_error == TRUE) { stop_(refer_to_name, " contains duplicate values in column '", colnames(x)[2], "'", call = FALSE) } else { return(FALSE) } } return(TRUE) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/mo_source.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Principal Component Analysis (for AMR) #' #' Performs a principal component analysis (PCA) based on a data set with automatic determination for afterwards plotting the groups and labels, and automatic filtering on only suitable (i.e. non-empty and numeric) variables. #' @param x a [data.frame] containing [numeric] columns #' @param ... columns of `x` to be selected for PCA, can be unquoted since it supports quasiquotation. #' @inheritParams stats::prcomp #' @details The [pca()] function takes a [data.frame] as input and performs the actual PCA with the \R function [prcomp()]. #' #' The result of the [pca()] function is a [prcomp] object, with an additional attribute `non_numeric_cols` which is a vector with the column names of all columns that do not contain [numeric] values. These are probably the groups and labels, and will be used by [ggplot_pca()]. #' @return An object of classes [pca] and [prcomp] #' @importFrom stats prcomp #' @export #' @examples #' # `example_isolates` is a data set available in the AMR package. #' # See ?example_isolates. #' #' \donttest{ #' if (require("dplyr")) { #' # calculate the resistance per group first #' resistance_data <- example_isolates %>% #' group_by( #' order = mo_order(mo), # group on anything, like order #' genus = mo_genus(mo) #' ) %>% # and genus as we do here; #' filter(n() >= 30) %>% # filter on only 30 results per group #' summarise_if(is.sir, resistance) # then get resistance of all drugs #' #' # now conduct PCA for certain antimicrobial drugs #' pca_result <- resistance_data %>% #' pca(AMC, CXM, CTX, CAZ, GEN, TOB, TMP, SXT) #' #' pca_result #' summary(pca_result) #' #' # old base R plotting method: #' biplot(pca_result) #' # new ggplot2 plotting method using this package: #' if (require("ggplot2")) { #' ggplot_pca(pca_result) #' #' ggplot_pca(pca_result) + #' scale_colour_viridis_d() + #' labs(title = "Title here") #' } #' } #' } pca <- function(x, ..., retx = TRUE, center = TRUE, scale. = TRUE, tol = NULL, rank. = NULL) { meet_criteria(x, allow_class = "data.frame") meet_criteria(retx, allow_class = "logical", has_length = 1) meet_criteria(center, allow_class = "logical", has_length = 1) meet_criteria(scale., allow_class = "logical", has_length = 1) meet_criteria(tol, allow_class = "numeric", has_length = 1, allow_NULL = TRUE) meet_criteria(rank., allow_class = "numeric", has_length = 1, allow_NULL = TRUE) # unset data.table, tibble, etc. # also removes groups made by dplyr::group_by x <- as.data.frame(x, stringsAsFactors = FALSE) x.bak <- x # defuse R expressions, this replaces rlang::enquos() dots <- substitute(list(...)) if (length(dots) > 1) { new_list <- list(0) for (i in seq_len(length(dots) - 1)) { new_list[[i]] <- tryCatch(eval(dots[[i + 1]], envir = x), error = function(e) stop(e$message, call. = FALSE) ) if (length(new_list[[i]]) == 1) { if (is.character(new_list[[i]]) && new_list[[i]] %in% colnames(x)) { # this is to support quoted variables: df %pm>% pca("mycol1", "mycol2") new_list[[i]] <- x[, new_list[[i]]] } else { # remove item - it's an argument like `center` new_list[[i]] <- NULL } } } x <- as.data.frame(new_list, stringsAsFactors = FALSE) if (any(vapply(FUN.VALUE = logical(1), x, function(y) !is.numeric(y)))) { warning_("in `pca()`: be sure to first calculate the resistance (or susceptibility) of variables with antimicrobial test results, since PCA works with numeric variables only. See Examples in ?pca.", call = FALSE) } # set column names tryCatch(colnames(x) <- as.character(dots)[2:length(dots)], error = function(e) warning("column names could not be set") ) # keep only numeric columns x <- x[, vapply(FUN.VALUE = logical(1), x, function(y) is.numeric(y)), drop = FALSE] # bind the data set with the non-numeric columns x <- cbind(x.bak[, vapply(FUN.VALUE = logical(1), x.bak, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE], x) } x <- pm_ungroup(x) # would otherwise select the grouping vars x <- x[rowSums(is.na(x)) == 0, ] # remove columns containing NAs pca_data <- x[, which(vapply(FUN.VALUE = logical(1), x, function(x) is.numeric(x))), drop = FALSE] message_( "Columns selected for PCA: ", vector_and(font_bold(colnames(pca_data), collapse = NULL), quotes = TRUE), ". Total observations available: ", nrow(pca_data), "." ) if (getRversion() < "3.4.0") { # stats::prcomp prior to 3.4.0 does not have the 'rank.' argument pca_model <- prcomp(pca_data, retx = retx, center = center, scale. = scale., tol = tol) } else { pca_model <- prcomp(pca_data, retx = retx, center = center, scale. = scale., tol = tol, rank. = rank.) } groups <- x[, vapply(FUN.VALUE = logical(1), x, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE] rownames(groups) <- NULL attr(pca_model, "non_numeric_cols") <- groups class(pca_model) <- c("pca", class(pca_model)) pca_model } #' @method print pca #' @export #' @noRd print.pca <- function(x, ...) { a <- attributes(x)$non_numeric_cols if (!is.null(a)) { print_pca_group(a) class(x) <- class(x)[class(x) != "pca"] } print(x, ...) } #' @method summary pca #' @export #' @noRd summary.pca <- function(object, ...) { a <- attributes(object)$non_numeric_cols if (!is.null(a)) { print_pca_group(a) class(object) <- class(object)[class(object) != "pca"] } summary(object, ...) } print_pca_group <- function(a) { grps <- sort(unique(a[, 1, drop = TRUE])) cat("Groups (n=", length(grps), ", named as '", colnames(a)[1], "'):\n", sep = "") print(grps) cat("\n") }
/scratch/gouwar.j/cran-all/cranData/AMR/R/pca.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Plotting for Classes `sir`, `mic` and `disk` #' #' Functions to plot classes `sir`, `mic` and `disk`, with support for base \R and `ggplot2`. #' @param x,object values created with [as.mic()], [as.disk()] or [as.sir()] (or their `random_*` variants, such as [random_mic()]) #' @param mo any (vector of) text that can be coerced to a valid microorganism code with [as.mo()] #' @param ab any (vector of) text that can be coerced to a valid antimicrobial drug code with [as.ab()] #' @param guideline interpretation guideline to use - the default is the latest included EUCAST guideline, see *Details* #' @param main,title title of the plot #' @param xlab,ylab axis title #' @param colours_SIR colours to use for filling in the bars, must be a vector of three values (in the order S, I and R). The default colours are colour-blind friendly. #' @param language language to be used to translate 'Susceptible', 'Increased exposure'/'Intermediate' and 'Resistant' - the default is system language (see [get_AMR_locale()]) and can be overwritten by setting the [package option][AMR-options] [`AMR_locale`][AMR-options], e.g. `options(AMR_locale = "de")`, see [translate]. Use `language = NULL` or `language = ""` to prevent translation. #' @param expand a [logical] to indicate whether the range on the x axis should be expanded between the lowest and highest value. For MIC values, intermediate values will be factors of 2 starting from the highest MIC value. For disk diameters, the whole diameter range will be filled. #' @inheritParams as.sir #' @details #' The interpretation of "I" will be named "Increased exposure" for all EUCAST guidelines since 2019, and will be named "Intermediate" in all other cases. #' #' For interpreting MIC values as well as disk diffusion diameters, supported guidelines to be used as input for the `guideline` argument are: `r vector_and(AMR::clinical_breakpoints$guideline, quotes = TRUE, reverse = TRUE)`. #' #' Simply using `"CLSI"` or `"EUCAST"` as input will automatically select the latest version of that guideline. #' @name plot #' @rdname plot #' @return The `autoplot()` functions return a [`ggplot`][ggplot2::ggplot()] model that is extendible with any `ggplot2` function. #' #' The `fortify()` functions return a [data.frame] as an extension for usage in the [ggplot2::ggplot()] function. #' @param ... arguments passed on to methods #' @examples #' some_mic_values <- random_mic(size = 100) #' some_disk_values <- random_disk(size = 100, mo = "Escherichia coli", ab = "cipro") #' some_sir_values <- random_sir(50, prob_SIR = c(0.55, 0.05, 0.30)) #' #' plot(some_mic_values) #' plot(some_disk_values) #' plot(some_sir_values) #' #' # when providing the microorganism and antibiotic, colours will show interpretations: #' plot(some_mic_values, mo = "S. aureus", ab = "ampicillin") #' plot(some_disk_values, mo = "Escherichia coli", ab = "cipro") #' plot(some_disk_values, mo = "Escherichia coli", ab = "cipro", language = "nl") #' #' \donttest{ #' if (require("ggplot2")) { #' autoplot(some_mic_values) #' } #' if (require("ggplot2")) { #' autoplot(some_disk_values, mo = "Escherichia coli", ab = "cipro") #' } #' if (require("ggplot2")) { #' autoplot(some_sir_values) #' } #' } NULL #' @method plot mic #' @importFrom graphics barplot axis mtext legend #' @export #' @rdname plot plot.mic <- function(x, mo = NULL, ab = NULL, guideline = "EUCAST", main = deparse(substitute(x)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Minimum Inhibitory Concentration (mg/L)", language = language), colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) if (length(colours_SIR) == 1) { colours_SIR <- rep(colours_SIR, 3) } main <- gsub(" +", " ", paste0(main, collapse = " ")) x <- plot_prepare_table(x, expand = expand) cols_sub <- plot_colours_subtitle_guideline( x = x, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, fn = as.mic, language = language, method = "MIC", include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) barplot(x, col = cols_sub$cols, main = main, ylim = c(0, max(x) * ifelse(any(colours_SIR %in% cols_sub$cols), 1.1, 1)), ylab = ylab, xlab = xlab, axes = FALSE ) axis(2, seq(0, max(x))) if (!is.null(cols_sub$sub)) { mtext(side = 3, line = 0.5, adj = 0.5, cex = 0.75, cols_sub$sub) } if (any(colours_SIR %in% cols_sub$cols)) { legend_txt <- character(0) legend_col <- character(0) if (any(cols_sub$cols == colours_SIR[1] & cols_sub$count > 0)) { legend_txt <- c(legend_txt, "(S) Susceptible") legend_col <- colours_SIR[1] } if (any(cols_sub$cols == colours_SIR[2] & cols_sub$count > 0)) { legend_txt <- c(legend_txt, paste("(I)", plot_name_of_I(cols_sub$guideline))) legend_col <- c(legend_col, colours_SIR[2]) } if (any(cols_sub$cols == colours_SIR[3] & cols_sub$count > 0)) { legend_txt <- c(legend_txt, "(R) Resistant") legend_col <- c(legend_col, colours_SIR[3]) } legend("top", x.intersp = 0.5, legend = translate_into_language(legend_txt, language = language), fill = legend_col, horiz = TRUE, cex = 0.75, box.lwd = 0, box.col = "#FFFFFF55", bg = "#FFFFFF55" ) } } #' @method barplot mic #' @export #' @noRd barplot.mic <- function(height, mo = NULL, ab = NULL, guideline = "EUCAST", main = deparse(substitute(height)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Minimum Inhibitory Concentration (mg/L)", language = language), colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, ...) { meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) main <- gsub(" +", " ", paste0(main, collapse = " ")) plot( x = height, main = main, ylab = ylab, xlab = xlab, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, ... ) } #' @method autoplot mic #' @rdname plot # will be exported using s3_register() in R/zzz.R autoplot.mic <- function(object, mo = NULL, ab = NULL, guideline = "EUCAST", title = deparse(substitute(object)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Minimum Inhibitory Concentration (mg/L)", language = language), colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { stop_ifnot_installed("ggplot2") meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) meet_criteria(title, allow_class = "character", allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) if ("main" %in% names(list(...))) { title <- list(...)$main } if (!is.null(title)) { title <- gsub(" +", " ", paste0(title, collapse = " ")) } x <- plot_prepare_table(object, expand = expand) cols_sub <- plot_colours_subtitle_guideline( x = x, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, fn = as.mic, language = language, method = "MIC", include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) df <- as.data.frame(x, stringsAsFactors = TRUE) colnames(df) <- c("mic", "count") df$cols <- cols_sub$cols df$cols[df$cols == colours_SIR[1]] <- "(S) Susceptible" df$cols[df$cols == colours_SIR[2]] <- paste("(I)", plot_name_of_I(cols_sub$guideline)) df$cols[df$cols == colours_SIR[3]] <- "(R) Resistant" df$cols <- factor(translate_into_language(df$cols, language = language), levels = translate_into_language( c( "(S) Susceptible", paste("(I)", plot_name_of_I(cols_sub$guideline)), "(R) Resistant" ), language = language ), ordered = TRUE ) p <- ggplot2::ggplot(df) if (any(colours_SIR %in% cols_sub$cols)) { vals <- c( "(S) Susceptible" = colours_SIR[1], "(I) Susceptible, incr. exp." = colours_SIR[2], "(I) Intermediate" = colours_SIR[2], "(R) Resistant" = colours_SIR[3] ) names(vals) <- translate_into_language(names(vals), language = language) p <- p + ggplot2::geom_col(ggplot2::aes(x = mic, y = count, fill = cols)) + # limits = force is needed because of a ggplot2 >= 3.3.4 bug (#4511) ggplot2::scale_fill_manual( values = vals, name = NULL, limits = force ) } else { p <- p + ggplot2::geom_col(ggplot2::aes(x = mic, y = count)) } p + ggplot2::labs(title = title, x = xlab, y = ylab, subtitle = cols_sub$sub) } #' @method fortify mic #' @rdname plot # will be exported using s3_register() in R/zzz.R fortify.mic <- function(object, ...) { stats::setNames( as.data.frame(plot_prepare_table(object, expand = FALSE)), c("x", "y") ) } #' @method plot disk #' @export #' @importFrom graphics barplot axis mtext legend #' @rdname plot plot.disk <- function(x, main = deparse(substitute(x)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Disk diffusion diameter (mm)", language = language), mo = NULL, ab = NULL, guideline = "EUCAST", colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) if (length(colours_SIR) == 1) { colours_SIR <- rep(colours_SIR, 3) } main <- gsub(" +", " ", paste0(main, collapse = " ")) x <- plot_prepare_table(x, expand = expand) cols_sub <- plot_colours_subtitle_guideline( x = x, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, fn = as.disk, language = language, method = "disk", include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) barplot(x, col = cols_sub$cols, main = main, ylim = c(0, max(x) * ifelse(any(colours_SIR %in% cols_sub$cols), 1.1, 1)), ylab = ylab, xlab = xlab, axes = FALSE ) axis(2, seq(0, max(x))) if (!is.null(cols_sub$sub)) { mtext(side = 3, line = 0.5, adj = 0.5, cex = 0.75, cols_sub$sub) } if (any(colours_SIR %in% cols_sub$cols)) { legend_txt <- character(0) legend_col <- character(0) if (any(cols_sub$cols == colours_SIR[3] & cols_sub$count > 0)) { legend_txt <- "(R) Resistant" legend_col <- colours_SIR[3] } if (any(cols_sub$cols == colours_SIR[2] & cols_sub$count > 0)) { legend_txt <- c(legend_txt, paste("(I)", plot_name_of_I(cols_sub$guideline))) legend_col <- c(legend_col, colours_SIR[2]) } if (any(cols_sub$cols == colours_SIR[1] & cols_sub$count > 0)) { legend_txt <- c(legend_txt, "(S) Susceptible") legend_col <- c(legend_col, colours_SIR[1]) } legend("top", x.intersp = 0.5, legend = translate_into_language(legend_txt, language = language), fill = legend_col, horiz = TRUE, cex = 0.75, box.lwd = 0, box.col = "#FFFFFF55", bg = "#FFFFFF55" ) } } #' @method barplot disk #' @export #' @noRd barplot.disk <- function(height, main = deparse(substitute(height)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Disk diffusion diameter (mm)", language = language), mo = NULL, ab = NULL, guideline = "EUCAST", colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, ...) { meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) main <- gsub(" +", " ", paste0(main, collapse = " ")) plot( x = height, main = main, ylab = ylab, xlab = xlab, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, ... ) } #' @method autoplot disk #' @rdname plot # will be exported using s3_register() in R/zzz.R autoplot.disk <- function(object, mo = NULL, ab = NULL, title = deparse(substitute(object)), ylab = translate_AMR("Frequency", language = language), xlab = translate_AMR("Disk diffusion diameter (mm)", language = language), guideline = "EUCAST", colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { stop_ifnot_installed("ggplot2") meet_criteria(title, allow_class = "character", allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE) meet_criteria(ab, allow_class = c("ab", "character"), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) if ("main" %in% names(list(...))) { title <- list(...)$main } if (!is.null(title)) { title <- gsub(" +", " ", paste0(title, collapse = " ")) } x <- plot_prepare_table(object, expand = expand) cols_sub <- plot_colours_subtitle_guideline( x = x, mo = mo, ab = ab, guideline = guideline, colours_SIR = colours_SIR, fn = as.disk, language = language, method = "disk", include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) df <- as.data.frame(x, stringsAsFactors = TRUE) colnames(df) <- c("disk", "count") df$cols <- cols_sub$cols df$cols[df$cols == colours_SIR[1]] <- "(S) Susceptible" df$cols[df$cols == colours_SIR[2]] <- paste("(I)", plot_name_of_I(cols_sub$guideline)) df$cols[df$cols == colours_SIR[3]] <- "(R) Resistant" df$cols <- factor(translate_into_language(df$cols, language = language), levels = translate_into_language( c( "(S) Susceptible", paste("(I)", plot_name_of_I(cols_sub$guideline)), "(R) Resistant" ), language = language ), ordered = TRUE ) p <- ggplot2::ggplot(df) if (any(colours_SIR %in% cols_sub$cols)) { vals <- c( "(S) Susceptible" = colours_SIR[1], "(I) Susceptible, incr. exp." = colours_SIR[2], "(I) Intermediate" = colours_SIR[2], "(R) Resistant" = colours_SIR[3] ) names(vals) <- translate_into_language(names(vals), language = language) p <- p + ggplot2::geom_col(ggplot2::aes(x = disk, y = count, fill = cols)) + # limits = force is needed because of a ggplot2 >= 3.3.4 bug (#4511) ggplot2::scale_fill_manual( values = vals, name = NULL, limits = force ) } else { p <- p + ggplot2::geom_col(ggplot2::aes(x = disk, y = count)) } p + ggplot2::labs(title = title, x = xlab, y = ylab, subtitle = cols_sub$sub) } #' @method fortify disk #' @rdname plot # will be exported using s3_register() in R/zzz.R fortify.disk <- function(object, ...) { stats::setNames( as.data.frame(plot_prepare_table(object, expand = FALSE)), c("x", "y") ) } #' @method plot sir #' @export #' @importFrom graphics plot text axis #' @rdname plot plot.sir <- function(x, ylab = translate_AMR("Percentage", language = language), xlab = translate_AMR("Antimicrobial Interpretation", language = language), main = deparse(substitute(x)), language = get_AMR_locale(), ...) { meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) data <- as.data.frame(table(x), stringsAsFactors = FALSE) colnames(data) <- c("x", "n") data$s <- round((data$n / sum(data$n)) * 100, 1) if (!"S" %in% data$x) { data <- rbind_AMR(data, data.frame(x = "S", n = 0, s = 0, stringsAsFactors = FALSE)) } if (!"I" %in% data$x) { data <- rbind_AMR(data, data.frame(x = "I", n = 0, s = 0, stringsAsFactors = FALSE)) } if (!"R" %in% data$x) { data <- rbind_AMR(data, data.frame(x = "R", n = 0, s = 0, stringsAsFactors = FALSE)) } data$x <- factor(data$x, levels = c("S", "I", "R"), ordered = TRUE) ymax <- pm_if_else(max(data$s) > 95, 105, 100) plot( x = data$x, y = data$s, lwd = 2, ylim = c(0, ymax), ylab = ylab, xlab = xlab, main = main, axes = FALSE ) # x axis axis(side = 1, at = 1:pm_n_distinct(data$x), labels = levels(data$x), lwd = 0) # y axis, 0-100% axis(side = 2, at = seq(0, 100, 5)) text( x = data$x, y = data$s + 4, labels = paste0(data$s, "% (n = ", data$n, ")") ) } #' @method barplot sir #' @importFrom graphics barplot axis #' @export #' @noRd barplot.sir <- function(height, main = deparse(substitute(height)), xlab = translate_AMR("Antimicrobial Interpretation", language = language), ylab = translate_AMR("Frequency", language = language), colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), expand = TRUE, ...) { meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(main, allow_class = "character", has_length = 1, allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) if ("colours_RSI" %in% names(list(...))) { deprecation_warning(extra_msg = "The 'colours_RSI' argument has been replaced with 'colours_SIR'.") colours_SIR <- list(...)$colours_RSI } meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) language <- validate_language(language) meet_criteria(expand, allow_class = "logical", has_length = 1) if (length(colours_SIR) == 1) { colours_SIR <- rep(colours_SIR, 3) } main <- gsub(" +", " ", paste0(main, collapse = " ")) x <- table(height) x <- x[c(1, 2, 3)] barplot(x, col = colours_SIR, xlab = xlab, main = main, ylab = ylab, axes = FALSE ) axis(2, seq(0, max(x))) } #' @method autoplot sir #' @rdname plot # will be exported using s3_register() in R/zzz.R autoplot.sir <- function(object, title = deparse(substitute(object)), xlab = translate_AMR("Antimicrobial Interpretation", language = language), ylab = translate_AMR("Frequency", language = language), colours_SIR = c("#3CAEA3", "#F6D55C", "#ED553B"), language = get_AMR_locale(), ...) { stop_ifnot_installed("ggplot2") meet_criteria(title, allow_class = "character", allow_NULL = TRUE) meet_criteria(ylab, allow_class = "character", has_length = 1) meet_criteria(xlab, allow_class = "character", has_length = 1) meet_criteria(colours_SIR, allow_class = "character", has_length = c(1, 3)) if ("main" %in% names(list(...))) { title <- list(...)$main } if (!is.null(title)) { title <- gsub(" +", " ", paste0(title, collapse = " ")) } if (length(colours_SIR) == 1) { colours_SIR <- rep(colours_SIR, 3) } df <- as.data.frame(table(object), stringsAsFactors = TRUE) colnames(df) <- c("sir", "count") ggplot2::ggplot(df) + ggplot2::geom_col(ggplot2::aes(x = sir, y = count, fill = sir)) + # limits = force is needed because of a ggplot2 >= 3.3.4 bug (#4511) ggplot2::scale_fill_manual( values = c( "S" = colours_SIR[1], "I" = colours_SIR[2], "R" = colours_SIR[3] ), limits = force ) + ggplot2::labs(title = title, x = xlab, y = ylab) + ggplot2::theme(legend.position = "none") } #' @method fortify sir #' @rdname plot # will be exported using s3_register() in R/zzz.R fortify.sir <- function(object, ...) { stats::setNames( as.data.frame(table(object)), c("x", "y") ) } plot_prepare_table <- function(x, expand) { x <- x[!is.na(x)] stop_if(length(x) == 0, "no observations to plot", call = FALSE) if (is.mic(x)) { if (expand == TRUE) { # expand range for MIC by adding factors of 2 from lowest to highest so all MICs in between also print valid_lvls <- levels(x) extra_range <- max(x) / 2 while (min(extra_range) / 2 > min(x)) { extra_range <- c(min(extra_range) / 2, extra_range) } nms <- extra_range extra_range <- rep(0, length(extra_range)) names(extra_range) <- nms x <- table(droplevels(x, as.mic = FALSE)) extra_range <- extra_range[!names(extra_range) %in% names(x) & names(extra_range) %in% valid_lvls] x <- as.table(c(x, extra_range)) } else { x <- table(droplevels(x, as.mic = FALSE)) } x <- x[order(as.double(as.mic(names(x))))] } else if (is.disk(x)) { if (expand == TRUE) { # expand range for disks from lowest to highest so all mm's in between also print extra_range <- rep(0, max(x) - min(x) - 1) names(extra_range) <- seq(min(x) + 1, max(x) - 1) x <- table(x) extra_range <- extra_range[!names(extra_range) %in% names(x)] x <- as.table(c(x, extra_range)) } else { x <- table(x) } x <- x[order(as.double(names(x)))] } as.table(x) } plot_name_of_I <- function(guideline) { if (guideline %unlike% "CLSI" && as.double(gsub("[^0-9]+", "", guideline)) >= 2019) { # interpretation since 2019 "Susceptible, incr. exp." } else { # interpretation until 2019 "Intermediate" } } plot_colours_subtitle_guideline <- function(x, mo, ab, guideline, colours_SIR, fn, language, method, breakpoint_type, include_PKPD, ...) { guideline <- get_guideline(guideline, AMR::clinical_breakpoints) # store previous interpretations to backup sir_history <- AMR_env$sir_interpretation_history # and clear previous interpretations AMR_env$sir_interpretation_history <- AMR_env$sir_interpretation_history[0, , drop = FALSE] if (!is.null(mo) && !is.null(ab)) { # interpret and give colour based on MIC values mo <- as.mo(mo) moname <- mo_name(mo, language = language) ab <- as.ab(ab) abname <- ab_name(ab, language = language) sir <- suppressWarnings(suppressMessages(as.sir(fn(names(x)), mo = mo, ab = ab, guideline = guideline, include_screening = FALSE, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ...))) guideline_txt <- guideline if (all(is.na(sir))) { sir_screening <- suppressWarnings(suppressMessages(as.sir(fn(names(x)), mo = mo, ab = ab, guideline = guideline, include_screening = TRUE, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ...))) if (!all(is.na(sir_screening))) { message_( "Only ", guideline, " ", method, " interpretations found for ", ab_name(ab, language = NULL, tolower = TRUE), " in ", italicise(moname), " for screening" ) sir <- sir_screening guideline_txt <- paste0("(Screen, ", guideline_txt, ")") } else { message_( "No ", guideline, " ", method, " interpretations found for ", ab_name(ab, language = NULL, tolower = TRUE), " in ", italicise(moname) ) guideline_txt <- paste0("(", guideline_txt, ")") } } else { if (isTRUE(list(...)$uti)) { guideline_txt <- paste("UTIs,", guideline_txt) } ref_tbl <- paste0('"', unique(AMR_env$sir_interpretation_history$ref_table), '"', collapse = "/") guideline_txt <- paste0("(", guideline_txt, ": ", ref_tbl, ")") } cols <- character(length = length(sir)) cols[is.na(sir)] <- "#BEBEBE" cols[sir == "S"] <- colours_SIR[1] cols[sir == "I"] <- colours_SIR[2] cols[sir == "R"] <- colours_SIR[3] sub <- bquote(.(abname) ~ "-" ~ italic(.(moname)) ~ .(guideline_txt)) } else { cols <- "#BEBEBE" sub <- NULL } # restore previous interpretations to backup AMR_env$sir_interpretation_history <- sir_history list(cols = cols, count = as.double(x), sub = sub, guideline = guideline) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/plot.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Calculate Antimicrobial Resistance #' #' @description These functions can be used to calculate the (co-)resistance or susceptibility of microbial isolates (i.e. percentage of S, SI, I, IR or R). All functions support quasiquotation with pipes, can be used in `summarise()` from the `dplyr` package and also support grouped variables, see *Examples*. #' #' [resistance()] should be used to calculate resistance, [susceptibility()] should be used to calculate susceptibility.\cr #' @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 antibiotics, see section *Combination Therapy* below #' @param data a [data.frame] containing columns with class [`sir`] (see [as.sir()]) #' @param translate_ab a column name of the [antibiotics] data set to translate the antibiotic abbreviations to, using [ab_property()] #' @inheritParams ab_property #' @param combine_SI a [logical] to indicate whether all values of S and I must be merged into one, so the output only consists of S+I vs. R (susceptible vs. resistant) - the default is `TRUE` #' @param ab_result antibiotic results to test against, must be one or more values of "S", "I", or "R" #' @param confidence_level the confidence level for the returned confidence interval. For the calculation, the number of S or SI isolates, and R isolates are compared with the total number of available isolates with R, S, or I by using [binom.test()], i.e., the Clopper-Pearson method. #' @param side the side of the confidence interval to return. The default is `"both"` for a length 2 vector, but can also be (abbreviated as) `"min"`/`"left"`/`"lower"`/`"less"` or `"max"`/`"right"`/`"higher"`/`"greater"`. #' @param collapse a [logical] to indicate whether the output values should be 'collapsed', i.e. be merged together into one value, or a character value to use for collapsing #' @inheritSection as.sir Interpretation of SIR #' @details #' **Remember that you should filter your data to let it contain only first isolates!** This is needed to exclude duplicates and to reduce selection bias. Use [first_isolate()] to determine them in your data set with one of the four available algorithms. #' #' The function [resistance()] is equal to the function [proportion_R()]. The function [susceptibility()] is equal to the function [proportion_SI()]. #' #' Use [sir_confidence_interval()] to calculate the confidence interval, which relies on [binom.test()], i.e., the Clopper-Pearson method. This function returns a vector of length 2 at default for antimicrobial *resistance*. Change the `side` argument to "left"/"min" or "right"/"max" to return a single value, and change the `ab_result` argument to e.g. `c("S", "I")` to test for antimicrobial *susceptibility*, see Examples. #' #' 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 antibiotics/variables that you test them for. See this example for two antibiotics, 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 include as include as include as include as #' numerator denominator numerator denominator #' -------- -------- ---------- ----------- ---------- ----------- #' 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. #' @source **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]. #' @rdname proportion #' @aliases portion #' @name proportion #' @export #' @examples #' # example_isolates is a data set available in the AMR package. #' # run ?example_isolates for more info. #' example_isolates #' #' #' # base R ------------------------------------------------------------ #' # determines %R #' resistance(example_isolates$AMX) #' sir_confidence_interval(example_isolates$AMX) #' sir_confidence_interval(example_isolates$AMX, #' confidence_level = 0.975 #' ) #' sir_confidence_interval(example_isolates$AMX, #' confidence_level = 0.975, #' collapse = ", " #' ) #' #' # determines %S+I: #' susceptibility(example_isolates$AMX) #' sir_confidence_interval(example_isolates$AMX, #' ab_result = c("S", "I") #' ) #' #' # be more specific #' proportion_S(example_isolates$AMX) #' proportion_SI(example_isolates$AMX) #' proportion_I(example_isolates$AMX) #' proportion_IR(example_isolates$AMX) #' proportion_R(example_isolates$AMX) #' #' # dplyr ------------------------------------------------------------- #' \donttest{ #' if (require("dplyr")) { #' example_isolates %>% #' group_by(ward) %>% #' summarise( #' r = resistance(CIP), #' n = n_sir(CIP) #' ) # n_sir works like n_distinct in dplyr, see ?n_sir #' } #' if (require("dplyr")) { #' example_isolates %>% #' group_by(ward) %>% #' summarise( #' cipro_R = resistance(CIP), #' ci_min = sir_confidence_interval(CIP, side = "min"), #' ci_max = sir_confidence_interval(CIP, side = "max"), #' ) #' } #' if (require("dplyr")) { #' # scoped dplyr verbs with antibiotic selectors #' # (you could also use across() of course) #' example_isolates %>% #' group_by(ward) %>% #' summarise_at( #' c(aminoglycosides(), carbapenems()), #' resistance #' ) #' } #' if (require("dplyr")) { #' example_isolates %>% #' group_by(ward) %>% #' summarise( #' R = resistance(CIP, as_percent = TRUE), #' SI = susceptibility(CIP, as_percent = TRUE), #' n1 = count_all(CIP), # the actual total; sum of all three #' n2 = n_sir(CIP), # same - analogous to n_distinct #' total = n() #' ) # NOT the number of tested isolates! #' #' # Calculate co-resistance between amoxicillin/clav acid and gentamicin, #' # so we can see that combination therapy does a lot more than mono therapy: #' example_isolates %>% susceptibility(AMC) # %SI = 76.3% #' example_isolates %>% count_all(AMC) # n = 1879 #' #' example_isolates %>% susceptibility(GEN) # %SI = 75.4% #' example_isolates %>% count_all(GEN) # n = 1855 #' #' example_isolates %>% susceptibility(AMC, GEN) # %SI = 94.1% #' example_isolates %>% count_all(AMC, GEN) # n = 1939 #' #' #' # See Details on how `only_all_tested` works. Example: #' example_isolates %>% #' summarise( #' numerator = count_susceptible(AMC, GEN), #' denominator = count_all(AMC, GEN), #' proportion = susceptibility(AMC, GEN) #' ) #' #' example_isolates %>% #' summarise( #' numerator = count_susceptible(AMC, GEN, only_all_tested = TRUE), #' denominator = count_all(AMC, GEN, only_all_tested = TRUE), #' proportion = susceptibility(AMC, GEN, only_all_tested = TRUE) #' ) #' #' #' example_isolates %>% #' group_by(ward) %>% #' summarise( #' cipro_p = susceptibility(CIP, as_percent = TRUE), #' cipro_n = count_all(CIP), #' genta_p = susceptibility(GEN, as_percent = TRUE), #' genta_n = count_all(GEN), #' combination_p = susceptibility(CIP, GEN, as_percent = TRUE), #' combination_n = count_all(CIP, GEN) #' ) #' #' # Get proportions S/I/R immediately of all sir columns #' example_isolates %>% #' select(AMX, CIP) %>% #' proportion_df(translate = FALSE) #' #' # It also supports grouping variables #' # (use sir_df to also include the count) #' example_isolates %>% #' select(ward, AMX, CIP) %>% #' group_by(ward) %>% #' sir_df(translate = FALSE) #' } #' } resistance <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "R", minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export susceptibility <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("S", "I"), minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export sir_confidence_interval <- function(..., ab_result = "R", minimum = 30, as_percent = FALSE, only_all_tested = FALSE, confidence_level = 0.95, side = "both", collapse = FALSE) { meet_criteria(ab_result, allow_class = c("character", "sir"), has_length = c(1, 2, 3), is_in = c("S", "I", "R")) 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) meet_criteria(only_all_tested, allow_class = "logical", has_length = 1) meet_criteria(confidence_level, allow_class = "numeric", is_positive = TRUE, has_length = 1) meet_criteria(side, allow_class = "character", has_length = 1, is_in = c("both", "b", "left", "l", "lower", "lowest", "less", "min", "right", "r", "higher", "highest", "greater", "g", "max")) meet_criteria(collapse, allow_class = c("logical", "character"), has_length = 1) x <- tryCatch( sir_calc(..., ab_result = ab_result, only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) n <- tryCatch( sir_calc(..., ab_result = c("S", "I", "R"), only_all_tested = only_all_tested, only_count = TRUE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) # this applies the Clopper-Pearson method out <- stats::binom.test(x = x, n = n, conf.level = confidence_level)$conf.int out <- set_clean_class(out, "double") if (side %in% c("left", "l", "lower", "lowest", "less", "min")) { out <- out[1] } else if (side %in% c("right", "r", "higher", "highest", "greater", "g", "max")) { out <- out[2] } if (isTRUE(as_percent)) { out <- percentage(out, digits = 1) } if (!isFALSE(collapse) && length(out) > 1) { if (is.numeric(out)) { out <- round(out, digits = 3) } out <- paste(out, collapse = ifelse(isTRUE(collapse), "-", collapse)) } if (n < minimum) { warning_("Introducing NA: ", ifelse(n == 0, "no", paste("only", n)), " results available for `sir_confidence_interval()` (`minimum` = ", minimum, ").", call = FALSE ) if (is.character(out)) { return(NA_character_) } else { return(NA_real_) } } out } #' @rdname proportion #' @export proportion_R <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "R", minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export proportion_IR <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("I", "R"), minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export proportion_I <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "I", minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export proportion_SI <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = c("S", "I"), minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export proportion_S <- function(..., minimum = 30, as_percent = FALSE, only_all_tested = FALSE) { tryCatch( sir_calc(..., ab_result = "S", minimum = minimum, as_percent = as_percent, only_all_tested = only_all_tested, only_count = FALSE ), error = function(e) stop_(gsub("in sir_calc(): ", "", e$message, fixed = TRUE), call = -5) ) } #' @rdname proportion #' @export proportion_df <- function(data, translate_ab = "name", language = get_AMR_locale(), minimum = 30, as_percent = FALSE, combine_SI = TRUE, confidence_level = 0.95) { tryCatch( sir_calc_df( type = "proportion", data = data, translate_ab = translate_ab, language = language, minimum = minimum, as_percent = as_percent, combine_SI = combine_SI, confidence_level = confidence_level ), error = function(e) stop_(gsub("in sir_calc_df(): ", "", e$message, fixed = TRUE), call = -5) ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/proportion.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Random MIC Values/Disk Zones/SIR Generation #' #' 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 drug, the generated results will reflect reality as much as possible. #' @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 drug code with [as.ab()] #' @param prob_SIR a vector of length 3: the probabilities for "S" (1st value), "I" (2nd value) and "R" (3rd value) #' @param ... ignored, only in place to allow future extensions #' @details The base \R function [sample()] is used for generating values. #' #' Generated values are based on the EUCAST `r max(as.integer(gsub("[^0-9]", "", subset(clinical_breakpoints, guideline %like% "EUCAST")$guideline)))` guideline as implemented in the [clinical_breakpoints] data set. To create specific generated values per bug or drug, set the `mo` and/or `ab` argument. #' @return class `mic` for [random_mic()] (see [as.mic()]) and class `disk` for [random_disk()] (see [as.disk()]) #' @name random #' @rdname random #' @export #' @examples #' random_mic(25) #' random_disk(25) #' random_sir(25) #' #' \donttest{ #' # make the random generation more realistic by setting a bug and/or drug: #' random_mic(25, "Klebsiella pneumoniae") # range 0.0625-64 #' random_mic(25, "Klebsiella pneumoniae", "meropenem") # range 0.0625-16 #' random_mic(25, "Streptococcus pneumoniae", "meropenem") # range 0.0625-4 #' #' random_disk(25, "Klebsiella pneumoniae") # range 8-50 #' random_disk(25, "Klebsiella pneumoniae", "ampicillin") # range 11-17 #' random_disk(25, "Streptococcus pneumoniae", "ampicillin") # range 12-27 #' } 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 = 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_sir <- function(size = NULL, prob_SIR = 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) if ("prob_RSI" %in% names(list(...))) { deprecation_warning("prob_RSI", "prob_SIR", is_function = FALSE) prob_SIR <- list(...)$prob_RSI } meet_criteria(prob_SIR, allow_class = c("numeric", "integer"), has_length = 3) if (is.null(size)) { size <- NROW(get_current_data(arg_name = "size", call = -3)) } sample(as.sir(c("S", "I", "R")), size = size, replace = TRUE, prob = prob_SIR) } random_exec <- function(method_type, size, mo = NULL, ab = NULL) { df <- AMR::clinical_breakpoints %pm>% pm_filter(guideline %like% "EUCAST") %pm>% pm_arrange(pm_desc(guideline)) %pm>% subset(guideline == max(guideline) & method == method_type & type == "human") if (!is.null(mo)) { mo_coerced <- as.mo(mo) mo_include <- c( mo_coerced, as.mo(mo_genus(mo_coerced)), as.mo(mo_family(mo_coerced)), as.mo(mo_order(mo_coerced)) ) df_new <- df %pm>% subset(mo %in% mo_include) if (nrow(df_new) > 0) { df <- df_new } else { warning_("in `random_", tolower(method_type), "()`: no rows found that match mo '", mo, "', ignoring argument `mo`") } } if (!is.null(ab)) { ab_coerced <- as.ab(ab) df_new <- df %pm>% subset(ab %in% ab_coerced) if (nrow(df_new) > 0) { df <- df_new } else { warning_("in `random_", tolower(method_type), "()`: no rows found that match ab '", ab, "' (", ab_name(ab_coerced, tolower = TRUE, language = NULL), "), ignoring argument `ab`") } } if (method_type == "MIC") { # 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, na.rm = TRUE)) + sample(c(1:3), 1) )] min_range <- mic_range[max( 1, which(mic_range == min(df$breakpoint_S, na.rm = TRUE)) - 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(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)]) } if (stats::runif(1) > 0.5) { out[out == max(out)] <- paste0(">=", out[out == max(out)]) } return(out) } else if (method_type == "DISK") { set_range <- seq( from = as.integer(min(df$breakpoint_R, na.rm = TRUE) / 1.25), to = as.integer(max(df$breakpoint_S, na.rm = TRUE) * 1.25), by = 1 ) out <- sample(set_range, size = size, replace = TRUE) out[out < 6] <- sample(c(6:10), length(out[out < 6]), replace = TRUE) out[out > 50] <- sample(c(40:50), length(out[out > 50]), replace = TRUE) return(as.disk(out)) } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/random.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Predict Antimicrobial Resistance #' #' Create a prediction model to predict antimicrobial resistance for the next years on statistical solid ground. Standard errors (SE) will be returned as columns `se_min` and `se_max`. See *Examples* for a real live example. #' @param object model data to be plotted #' @param col_ab column name of `x` containing antimicrobial interpretations (`"R"`, `"I"` and `"S"`) #' @param col_date column name of the date, will be used to calculate years if this column doesn't consist of years already - the default is the first column of with a date class #' @param year_min lowest year to use in the prediction model, dafaults to the lowest year in `col_date` #' @param year_max highest year to use in the prediction model - the default is 10 years after today #' @param year_every unit of sequence between lowest year found in the data and `year_max` #' @param minimum minimal amount of available isolates per year to include. Years containing less observations will be estimated by the model. #' @param model the statistical model of choice. This could be a generalised linear regression model with binomial distribution (i.e. using `glm(..., family = binomial)`, assuming that a period of zero resistance was followed by a period of increasing resistance leading slowly to more and more resistance. See *Details* for all valid options. #' @param I_as_S a [logical] to indicate whether values `"I"` should be treated as `"S"` (will otherwise be treated as `"R"`). The default, `TRUE`, follows the redefinition by EUCAST about the interpretation of I (increased exposure) in 2019, see section *Interpretation of S, I and R* below. #' @param preserve_measurements a [logical] to indicate whether predictions of years that are actually available in the data should be overwritten by the original data. The standard errors of those years will be `NA`. #' @param info a [logical] to indicate whether textual analysis should be printed with the name and [summary()] of the statistical model. #' @param main title of the plot #' @param ribbon a [logical] to indicate whether a ribbon should be shown (default) or error bars #' @param ... arguments passed on to functions #' @inheritSection as.sir Interpretation of SIR #' @inheritParams first_isolate #' @inheritParams graphics::plot #' @details Valid options for the statistical model (argument `model`) are: #' - `"binomial"` or `"binom"` or `"logit"`: a generalised linear regression model with binomial distribution #' - `"loglin"` or `"poisson"`: a generalised log-linear regression model with poisson distribution #' - `"lin"` or `"linear"`: a linear regression model #' @return A [data.frame] with extra class [`resistance_predict`] with columns: #' - `year` #' - `value`, the same as `estimated` when `preserve_measurements = FALSE`, and a combination of `observed` and `estimated` otherwise #' - `se_min`, the lower bound of the standard error with a minimum of `0` (so the standard error will never go below 0%) #' - `se_max` the upper bound of the standard error with a maximum of `1` (so the standard error will never go above 100%) #' - `observations`, the total number of available observations in that year, i.e. \eqn{S + I + R} #' - `observed`, the original observed resistant percentages #' - `estimated`, the estimated resistant percentages, calculated by the model #' #' Furthermore, the model itself is available as an attribute: `attributes(x)$model`, see *Examples*. #' @seealso The [proportion()] functions to calculate resistance #' #' Models: [lm()] [glm()] #' @rdname resistance_predict #' @export #' @importFrom stats predict glm lm #' @examples #' x <- resistance_predict(example_isolates, #' col_ab = "AMX", #' year_min = 2010, #' model = "binomial" #' ) #' plot(x) #' \donttest{ #' if (require("ggplot2")) { #' ggplot_sir_predict(x) #' } #' #' # using dplyr: #' if (require("dplyr")) { #' x <- example_isolates %>% #' filter_first_isolate() %>% #' filter(mo_genus(mo) == "Staphylococcus") %>% #' resistance_predict("PEN", model = "binomial") #' print(plot(x)) #' #' # get the model from the object #' mymodel <- attributes(x)$model #' summary(mymodel) #' } #' #' # create nice plots with ggplot2 yourself #' if (require("dplyr") && require("ggplot2")) { #' data <- example_isolates %>% #' filter(mo == as.mo("E. coli")) %>% #' resistance_predict( #' col_ab = "AMX", #' col_date = "date", #' model = "binomial", #' info = FALSE, #' minimum = 15 #' ) #' head(data) #' autoplot(data) #' } #' } resistance_predict <- function(x, col_ab, col_date = NULL, year_min = NULL, year_max = NULL, year_every = 1, minimum = 30, model = NULL, I_as_S = TRUE, preserve_measurements = TRUE, info = interactive(), ...) { meet_criteria(x, allow_class = "data.frame") meet_criteria(col_ab, allow_class = "character", has_length = 1, is_in = colnames(x)) meet_criteria(col_date, allow_class = "character", has_length = 1, is_in = colnames(x), allow_NULL = TRUE) meet_criteria(year_min, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive = TRUE, is_finite = TRUE) meet_criteria(year_max, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE, is_positive = TRUE, is_finite = TRUE) meet_criteria(year_every, allow_class = c("numeric", "integer"), has_length = 1, is_positive = TRUE, is_finite = TRUE) meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, is_positive_or_zero = TRUE, is_finite = TRUE) meet_criteria(model, allow_class = c("character", "function"), has_length = 1, allow_NULL = TRUE) meet_criteria(I_as_S, allow_class = "logical", has_length = 1) meet_criteria(preserve_measurements, allow_class = "logical", has_length = 1) meet_criteria(info, allow_class = "logical", has_length = 1) stop_if(is.null(model), 'choose a regression model with the `model` argument, e.g. resistance_predict(..., model = "binomial")') x.bak <- x x <- as.data.frame(x, stringsAsFactors = FALSE) # -- date if (is.null(col_date)) { col_date <- search_type_in_df(x = x, type = "date") stop_if(is.null(col_date), "`col_date` must be set") } stop_ifnot( col_date %in% colnames(x), "column '", col_date, "' not found" ) year <- function(x) { # don't depend on lubridate or so, would be overkill for only this function if (all(grepl("^[0-9]{4}$", x))) { as.integer(x) } else { as.integer(format(as.Date(x), "%Y")) } } df <- x df[, col_ab] <- droplevels(as.sir(df[, col_ab, drop = TRUE])) if (I_as_S == TRUE) { # then I as S df[, col_ab] <- gsub("I", "S", df[, col_ab, drop = TRUE], fixed = TRUE) } else { # then I as R df[, col_ab] <- gsub("I", "R", df[, col_ab, drop = TRUE], fixed = TRUE) } df[, col_ab] <- ifelse(is.na(df[, col_ab, drop = TRUE]), 0, df[, col_ab, drop = TRUE]) # remove rows with NAs df <- subset(df, !is.na(df[, col_ab, drop = TRUE])) df$year <- year(df[, col_date, drop = TRUE]) df <- as.data.frame(rbind(table(df[, c("year", col_ab), drop = FALSE])), stringsAsFactors = FALSE ) df$year <- as.integer(rownames(df)) rownames(df) <- NULL df <- subset(df, sum(df$R + df$S, na.rm = TRUE) >= minimum) # nolint start df_matrix <- as.matrix(df[, c("R", "S"), drop = FALSE]) # nolint end stop_if(NROW(df) == 0, "there are no observations") year_lowest <- min(df$year) if (is.null(year_min)) { year_min <- year_lowest } else { year_min <- max(year_min, year_lowest, na.rm = TRUE) } if (is.null(year_max)) { year_max <- year(Sys.Date()) + 10 } years <- list(year = seq(from = year_min, to = year_max, by = year_every)) if (model %in% c("binomial", "binom", "logit")) { model <- "binomial" model_lm <- with(df, glm(df_matrix ~ year, family = binomial)) if (isTRUE(info)) { cat("\nLogistic regression model (logit) with binomial distribution") cat("\n------------------------------------------------------------\n") print(summary(model_lm)) } predictmodel <- predict(model_lm, newdata = years, type = "response", se.fit = TRUE) prediction <- predictmodel$fit se <- predictmodel$se.fit } else if (model %in% c("loglin", "poisson")) { model <- "poisson" model_lm <- with(df, glm(R ~ year, family = poisson)) if (isTRUE(info)) { cat("\nLog-linear regression model (loglin) with poisson distribution") cat("\n--------------------------------------------------------------\n") print(summary(model_lm)) } predictmodel <- predict(model_lm, newdata = years, type = "response", se.fit = TRUE) prediction <- predictmodel$fit se <- predictmodel$se.fit } else if (model %in% c("lin", "linear")) { model <- "linear" model_lm <- with(df, lm((R / (R + S)) ~ year)) if (isTRUE(info)) { cat("\nLinear regression model") cat("\n-----------------------\n") print(summary(model_lm)) } predictmodel <- predict(model_lm, newdata = years, se.fit = TRUE) prediction <- predictmodel$fit se <- predictmodel$se.fit } else { stop("no valid model selected. See ?resistance_predict.") } # prepare the output dataframe df_prediction <- data.frame( year = unlist(years), value = prediction, se_min = prediction - se, se_max = prediction + se, stringsAsFactors = FALSE ) if (model == "poisson") { df_prediction$value <- as.integer(format(df_prediction$value, scientific = FALSE)) df_prediction$se_min <- as.integer(df_prediction$se_min) df_prediction$se_max <- as.integer(df_prediction$se_max) } else { # se_max not above 1 df_prediction$se_max <- pmin(df_prediction$se_max, 1) } # se_min not below 0 df_prediction$se_min <- pmax(df_prediction$se_min, 0) df_observations <- data.frame( year = df$year, observations = df$R + df$S, observed = df$R / (df$R + df$S), stringsAsFactors = FALSE ) df_prediction <- df_prediction %pm>% pm_left_join(df_observations, by = "year") df_prediction$estimated <- df_prediction$value if (preserve_measurements == TRUE) { # replace estimated data by observed data df_prediction$value <- ifelse(!is.na(df_prediction$observed), df_prediction$observed, df_prediction$value) df_prediction$se_min <- ifelse(!is.na(df_prediction$observed), NA, df_prediction$se_min) df_prediction$se_max <- ifelse(!is.na(df_prediction$observed), NA, df_prediction$se_max) } df_prediction$value <- ifelse(df_prediction$value > 1, 1, pmax(df_prediction$value, 0)) df_prediction <- df_prediction[order(df_prediction$year), , drop = FALSE] out <- as_original_data_class(df_prediction, class(x.bak)) # will remove tibble groups structure(out, class = c("resistance_predict", class(out)), I_as_S = I_as_S, model_title = model, model = model_lm, ab = col_ab ) } #' @rdname resistance_predict #' @export sir_predict <- resistance_predict #' @method plot resistance_predict #' @export #' @importFrom graphics plot axis arrows points #' @rdname resistance_predict plot.resistance_predict <- function(x, main = paste("Resistance Prediction of", x_name), ...) { x_name <- paste0(ab_name(attributes(x)$ab), " (", attributes(x)$ab, ")") meet_criteria(main, allow_class = "character", has_length = 1) if (attributes(x)$I_as_S == TRUE) { ylab <- "%R" } else { ylab <- "%IR" } plot( x = x$year, y = x$value, ylim = c(0, 1), yaxt = "n", # no y labels pch = 19, # closed dots ylab = paste0("Percentage (", ylab, ")"), xlab = "Year", main = main, sub = paste0( "(n = ", sum(x$observations, na.rm = TRUE), ", model: ", attributes(x)$model_title, ")" ), cex.sub = 0.75 ) axis(side = 2, at = seq(0, 1, 0.1), labels = paste0(0:10 * 10, "%")) # hack for error bars: https://stackoverflow.com/a/22037078/4575331 arrows( x0 = x$year, y0 = x$se_min, x1 = x$year, y1 = x$se_max, length = 0.05, angle = 90, code = 3, lwd = 1.5 ) # overlay grey points for prediction points( x = subset(x, is.na(observations))$year, y = subset(x, is.na(observations))$value, pch = 19, col = "grey40" ) } #' @rdname resistance_predict #' @export ggplot_sir_predict <- function(x, main = paste("Resistance Prediction of", x_name), ribbon = TRUE, ...) { x_name <- paste0(ab_name(attributes(x)$ab), " (", attributes(x)$ab, ")") meet_criteria(main, allow_class = "character", has_length = 1) meet_criteria(ribbon, allow_class = "logical", has_length = 1) stop_ifnot_installed("ggplot2") stop_ifnot(inherits(x, "resistance_predict"), "`x` must be a resistance prediction model created with resistance_predict()") if (attributes(x)$I_as_S == TRUE) { ylab <- "%R" } else { ylab <- "%IR" } p <- ggplot2::ggplot( as.data.frame(x, stringsAsFactors = FALSE), ggplot2::aes(x = year, y = value) ) + ggplot2::geom_point( data = subset(x, !is.na(observations)), size = 2 ) + scale_y_percent(limits = c(0, 1)) + ggplot2::labs( title = main, y = paste0("Percentage (", ylab, ")"), x = "Year", caption = paste0( "(n = ", sum(x$observations, na.rm = TRUE), ", model: ", attributes(x)$model_title, ")" ) ) if (ribbon == TRUE) { p <- p + ggplot2::geom_ribbon(ggplot2::aes(ymin = se_min, ymax = se_max), alpha = 0.25) } else { p <- p + ggplot2::geom_errorbar(ggplot2::aes(ymin = se_min, ymax = se_max), na.rm = TRUE, width = 0.5) } p <- p + # overlay grey points for prediction ggplot2::geom_point( data = subset(x, is.na(observations)), size = 2, colour = "grey40" ) p } #' @method autoplot resistance_predict #' @rdname resistance_predict # will be exported using s3_register() in R/zzz.R autoplot.resistance_predict <- function(object, main = paste("Resistance Prediction of", x_name), ribbon = TRUE, ...) { x_name <- paste0(ab_name(attributes(object)$ab), " (", attributes(object)$ab, ")") meet_criteria(main, allow_class = "character", has_length = 1) meet_criteria(ribbon, allow_class = "logical", has_length = 1) ggplot_sir_predict(x = object, main = main, ribbon = ribbon, ...) } #' @method fortify resistance_predict #' @noRd # will be exported using s3_register() in R/zzz.R fortify.resistance_predict <- function(model, data, ...) { as.data.frame(model) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/resistance_predict.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Translate MIC and Disk Diffusion to SIR, or Clean Existing SIR Data #' #' @description Interpret minimum inhibitory concentration (MIC) values and disk diffusion diameters according to EUCAST or CLSI, or clean up existing SIR values. This transforms the input to a new class [`sir`], which is an ordered [factor] with levels `S < I < R`. #' #' Currently available **breakpoint guidelines** are EUCAST `r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))` and CLSI `r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`, and available **breakpoint types** are `r vector_and(clinical_breakpoints$type)`. #' #' All breakpoints used for interpretation are publicly available in the [clinical_breakpoints] data set. #' @rdname as.sir #' @param x vector of values (for class [`mic`]: MIC values in mg/L, for class [`disk`]: a disk diffusion radius in millimetres) #' @param mo any (vector of) text that can be coerced to valid microorganism codes with [as.mo()], can be left empty to determine it automatically #' @param ab any (vector of) text that can be coerced to a valid antimicrobial drug code with [as.ab()] #' @param uti (Urinary Tract Infection) A vector with [logical]s (`TRUE` or `FALSE`) to specify whether a UTI specific interpretation from the guideline should be chosen. For using [as.sir()] on a [data.frame], this can also be a column containing [logical]s or when left blank, the data set will be searched for a column 'specimen', and rows within this column containing 'urin' (such as 'urine', 'urina') will be regarded isolates from a UTI. See *Examples*. #' @inheritParams first_isolate #' @param guideline defaults to EUCAST `r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))` (the latest implemented EUCAST guideline in the [AMR::clinical_breakpoints] data set), but can be set with the [package option][AMR-options] [`AMR_guideline`][AMR-options]. Currently supports EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`), see *Details*. #' @param conserve_capped_values a [logical] to indicate that MIC values starting with `">"` (but not `">="`) must always return "R" , and that MIC values starting with `"<"` (but not `"<="`) must always return "S" #' @param add_intrinsic_resistance *(only useful when using a EUCAST guideline)* a [logical] to indicate whether intrinsic antibiotic resistance must also be considered for applicable bug-drug combinations, meaning that e.g. ampicillin will always return "R" in *Klebsiella* species. Determination is based on the [intrinsic_resistant] data set, that itself is based on `r format_eucast_version_nr(3.3)`. #' @param include_screening a [logical] to indicate that clinical breakpoints for screening are allowed - the default is `FALSE`. Can also be set with the [package option][AMR-options] [`AMR_include_screening`][AMR-options]. #' @param include_PKPD a [logical] to indicate that PK/PD clinical breakpoints must be applied as a last resort - the default is `TRUE`. Can also be set with the [package option][AMR-options] [`AMR_include_PKPD`][AMR-options]. #' @param breakpoint_type the type of breakpoints to use, either `r vector_or(clinical_breakpoints$type)`. ECOFF stands for Epidemiological Cut-Off values. The default is `"human"`, which can also be set with the [package option][AMR-options] [`AMR_breakpoint_type`][AMR-options]. #' @param reference_data a [data.frame] to be used for interpretation, which defaults to the [clinical_breakpoints] data set. Changing this argument allows for using own interpretation guidelines. This argument must contain a data set that is equal in structure to the [clinical_breakpoints] data set (same column names and column types). Please note that the `guideline` argument will be ignored when `reference_data` is manually set. #' @param threshold maximum fraction of invalid antimicrobial interpretations of `x`, see *Examples* #' @param ... for using on a [data.frame]: names of columns to apply [as.sir()] on (supports tidy selection such as `column1:column4`). Otherwise: arguments passed on to methods. #' @details #' *Note: The clinical breakpoints in this package were validated through and imported from [WHONET](https://whonet.org) and the public use of this `AMR` package has been endorsed by CLSI and EUCAST, please see [clinical_breakpoints] for more information.* #' #' ### How it Works #' #' The [as.sir()] function works in four ways: #' #' 1. For **cleaning raw / untransformed data**. The data will be cleaned to only contain values S, I and R and will try its best to determine this with some intelligence. For example, mixed values with SIR interpretations and MIC values such as `"<0.25; S"` will be coerced to `"S"`. Combined interpretations for multiple test methods (as seen in laboratory records) such as `"S; S"` will be coerced to `"S"`, but a value like `"S; I"` will return `NA` with a warning that the input is unclear. #' #' 2. For **interpreting minimum inhibitory concentration (MIC) values** according to EUCAST or CLSI. You must clean your MIC values first using [as.mic()], that also gives your columns the new data class [`mic`]. Also, be sure to have a column with microorganism names or codes. It will be found automatically, but can be set manually using the `mo` argument. #' * Using `dplyr`, SIR interpretation can be done very easily with either: #' ``` #' your_data %>% mutate_if(is.mic, as.sir) #' your_data %>% mutate(across(where(is.mic), as.sir)) #' ``` #' * Operators like "<=" will be stripped before interpretation. When using `conserve_capped_values = TRUE`, an MIC value of e.g. ">2" will always return "R", even if the breakpoint according to the chosen guideline is ">=4". This is to prevent that capped values from raw laboratory data would not be treated conservatively. The default behaviour (`conserve_capped_values = FALSE`) considers ">2" to be lower than ">=4" and might in this case return "S" or "I". #' 3. For **interpreting disk diffusion diameters** according to EUCAST or CLSI. You must clean your disk zones first using [as.disk()], that also gives your columns the new data class [`disk`]. Also, be sure to have a column with microorganism names or codes. It will be found automatically, but can be set manually using the `mo` argument. #' * Using `dplyr`, SIR interpretation can be done very easily with either: #' ``` #' your_data %>% mutate_if(is.disk, as.sir) #' your_data %>% mutate(across(where(is.disk), as.sir)) #' ``` #' 4. For **interpreting a complete data set**, with automatic determination of MIC values, disk diffusion diameters, microorganism names or codes, and antimicrobial test results. This is done very simply by running `as.sir(your_data)`. #' #' **For points 2, 3 and 4: Use [sir_interpretation_history()]** to retrieve a [data.frame] (or [tibble][tibble::tibble()] if the `tibble` package is installed) with all results of the last [as.sir()] call. #' #' ### Supported Guidelines #' #' For interpreting MIC values as well as disk diffusion diameters, currently implemented guidelines are EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`). #' #' Thus, the `guideline` argument must be set to e.g., ``r paste0('"', subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline[1], '"')`` or ``r paste0('"', subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline[1], '"')``. By simply using `"EUCAST"` (the default) or `"CLSI"` as input, the latest included version of that guideline will automatically be selected. You can set your own data set using the `reference_data` argument. The `guideline` argument will then be ignored. #' #' You can set the default guideline with the [package option][AMR-options] [`AMR_guideline`][AMR-options] (e.g. in your `.Rprofile` file), such as: #' #' ``` #' options(AMR_guideline = "CLSI") #' options(AMR_guideline = "CLSI 2018") #' options(AMR_guideline = "EUCAST 2020") #' # or to reset: #' options(AMR_guideline = NULL) #' ``` #' #' ### After Interpretation #' #' After using [as.sir()], you can use the [eucast_rules()] defined by EUCAST to (1) apply inferred susceptibility and resistance based on results of other antimicrobials and (2) apply intrinsic resistance based on taxonomic properties of a microorganism. #' #' ### Machine-Readable Clinical Breakpoints #' #' The repository of this package [contains a machine-readable version](https://github.com/msberends/AMR/blob/main/data-raw/clinical_breakpoints.txt) of all guidelines. This is a CSV file consisting of `r format(nrow(AMR::clinical_breakpoints), big.mark = " ")` rows and `r ncol(AMR::clinical_breakpoints)` columns. This file is machine-readable, since it contains one row for every unique combination of the test method (MIC or disk diffusion), the antimicrobial drug and the microorganism. **This allows for easy implementation of these rules in laboratory information systems (LIS)**. Note that it only contains interpretation guidelines for humans - interpretation guidelines from CLSI for animals were removed. #' #' ### Other #' #' The function [is.sir()] detects if the input contains class `sir`. If the input is a [data.frame], it iterates over all columns and returns a [logical] vector. #' #' The function [is_sir_eligible()] returns `TRUE` when a columns contains at most 5% invalid antimicrobial interpretations (not S and/or I and/or R), and `FALSE` otherwise. The threshold of 5% can be set with the `threshold` argument. If the input is a [data.frame], it iterates over all columns and returns a [logical] vector. #' @section Interpretation of SIR: #' In 2019, the European Committee on Antimicrobial Susceptibility Testing (EUCAST) has decided to change the definitions of susceptibility testing categories S, I, and R as shown below (<https://www.eucast.org/newsiandr>): #' #' - **S - Susceptible, standard dosing regimen**\cr #' A microorganism is categorised as "Susceptible, standard dosing regimen", when there is a high likelihood of therapeutic success using a standard dosing regimen of the agent. #' - **I - Susceptible, increased exposure** *\cr #' A microorganism is categorised as "Susceptible, Increased exposure*" when there is a high likelihood of therapeutic success because exposure to the agent is increased by adjusting the dosing regimen or by its concentration at the site of infection. #' - **R = Resistant**\cr #' A microorganism is categorised as "Resistant" when there is a high likelihood of therapeutic failure even when there is increased exposure. #' #' * *Exposure* is a function of how the mode of administration, dose, dosing interval, infusion time, as well as distribution and excretion of the antimicrobial agent will influence the infecting organism at the site of infection. #' #' This AMR package honours this insight. Use [susceptibility()] (equal to [proportion_SI()]) to determine antimicrobial susceptibility and [count_susceptible()] (equal to [count_SI()]) to count susceptible isolates. #' @return Ordered [factor] with new class `sir` #' @aliases sir #' @export #' @seealso [as.mic()], [as.disk()], [as.mo()] #' @source #' For interpretations of minimum inhibitory concentration (MIC) values and disk diffusion diameters: #' #' - **M39 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data**, `r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`, *Clinical and Laboratory Standards Institute* (CLSI). <https://clsi.org/standards/products/microbiology/documents/m39/>. #' - **M100 Performance Standard for Antimicrobial Susceptibility Testing**, `r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "CLSI")$guideline)))`, *Clinical and Laboratory Standards Institute* (CLSI). <https://clsi.org/standards/products/microbiology/documents/m100/>. #' - **Breakpoint tables for interpretation of MICs and zone diameters**, `r min(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(AMR::clinical_breakpoints, guideline %like% "EUCAST")$guideline)))`, *European Committee on Antimicrobial Susceptibility Testing* (EUCAST). <https://www.eucast.org/clinical_breakpoints>. #' @inheritSection AMR Reference Data Publicly Available #' @examples #' example_isolates #' summary(example_isolates) # see all SIR results at a glance #' #' # For INTERPRETING disk diffusion and MIC values ----------------------- #' #' # a whole data set, even with combined MIC values and disk zones #' df <- data.frame( #' microorganism = "Escherichia coli", #' AMP = as.mic(8), #' CIP = as.mic(0.256), #' GEN = as.disk(18), #' TOB = as.disk(16), #' ERY = "R" #' ) #' as.sir(df) #' #' # return a 'logbook' about the results: #' sir_interpretation_history() #' #' # for single values #' as.sir( #' x = as.mic(2), #' mo = as.mo("S. pneumoniae"), #' ab = "AMP", #' guideline = "EUCAST" #' ) #' #' as.sir( #' x = as.disk(18), #' mo = "Strep pneu", # `mo` will be coerced with as.mo() #' ab = "ampicillin", # and `ab` with as.ab() #' guideline = "EUCAST" #' ) #' #' \donttest{ #' # the dplyr way #' if (require("dplyr")) { #' df %>% mutate_if(is.mic, as.sir) #' df %>% mutate_if(function(x) is.mic(x) | is.disk(x), as.sir) #' df %>% mutate(across(where(is.mic), as.sir)) #' df %>% mutate_at(vars(AMP:TOB), as.sir) #' df %>% mutate(across(AMP:TOB, as.sir)) #' #' df %>% #' mutate_at(vars(AMP:TOB), as.sir, mo = .$microorganism) #' #' # to include information about urinary tract infections (UTI) #' data.frame( #' mo = "E. coli", #' NIT = c("<= 2", 32), #' from_the_bladder = c(TRUE, FALSE) #' ) %>% #' as.sir(uti = "from_the_bladder") #' #' data.frame( #' mo = "E. coli", #' NIT = c("<= 2", 32), #' specimen = c("urine", "blood") #' ) %>% #' as.sir() # automatically determines urine isolates #' #' df %>% #' mutate_at(vars(AMP:TOB), as.sir, mo = "E. coli", uti = TRUE) #' } #' #' # For CLEANING existing SIR values ------------------------------------ #' #' as.sir(c("S", "I", "R", "A", "B", "C")) #' as.sir("<= 0.002; S") # will return "S" #' sir_data <- as.sir(c(rep("S", 474), rep("I", 36), rep("R", 370))) #' is.sir(sir_data) #' plot(sir_data) # for percentages #' barplot(sir_data) # for frequencies #' #' # the dplyr way #' if (require("dplyr")) { #' example_isolates %>% #' mutate_at(vars(PEN:RIF), as.sir) #' # same: #' example_isolates %>% #' as.sir(PEN:RIF) #' #' # fastest way to transform all columns with already valid AMR results to class `sir`: #' example_isolates %>% #' mutate_if(is_sir_eligible, as.sir) #' #' # since dplyr 1.0.0, this can also be: #' # example_isolates %>% #' # mutate(across(where(is_sir_eligible), as.sir)) #' } #' } as.sir <- function(x, ...) { UseMethod("as.sir") } #' @rdname as.sir #' @details `NA_sir_` is a missing value of the new `sir` class, analogous to e.g. base \R's [`NA_character_`][base::NA]. #' @export NA_sir_ <- set_clean_class(factor(NA_character_, levels = c("S", "I", "R"), ordered = TRUE), new_class = c("sir", "ordered", "factor") ) #' @rdname as.sir #' @export is.sir <- function(x) { if (inherits(x, "data.frame")) { unname(vapply(FUN.VALUE = logical(1), x, is.sir)) } else { rsi <- inherits(x, "rsi") sir <- inherits(x, "sir") if (isTRUE(rsi) && message_not_thrown_before("is.sir-rsi")) { deprecation_warning(extra_msg = "The 'rsi' class has been replaced with 'sir'. Transform your 'rsi' columns to 'sir' with `as.sir()`, e.g.:\n your_data %>% mutate_if(is.rsi, as.sir)") } isTRUE(rsi) || isTRUE(sir) } } #' @rdname as.sir #' @export is_sir_eligible <- function(x, threshold = 0.05) { meet_criteria(threshold, allow_class = "numeric", has_length = 1) if (inherits(x, "data.frame")) { # iterate this function over all columns return(unname(vapply(FUN.VALUE = logical(1), x, is_sir_eligible))) } stop_if(NCOL(x) > 1, "`x` must be a one-dimensional vector.") if (any(c( "numeric", "integer", "mo", "ab", "Date", "POSIXt", "raw", "hms", "mic", "disk" ) %in% class(x))) { # no transformation needed return(FALSE) } else if (all(x %in% c("S", "I", "R", NA)) & !all(is.na(x))) { return(TRUE) } else if (!any(c("S", "I", "R") %in% x, na.rm = TRUE) & !all(is.na(x))) { return(FALSE) } else { x <- x[!is.na(x) & !is.null(x) & !x %in% c("", "-", "NULL")] if (length(x) == 0) { # no other values than empty cur_col <- get_current_column() if (!is.null(cur_col)) { ab <- suppressWarnings(as.ab(cur_col, fast_mode = TRUE, info = FALSE)) if (!is.na(ab)) { # this is a valid antibiotic drug code message_( "Column '", font_bold(cur_col), "' is SIR eligible (despite only having empty values), since it seems to be ", ab_name(ab, language = NULL, tolower = TRUE), " (", ab, ")" ) return(TRUE) } } # all values empty and no antibiotic col name - return FALSE return(FALSE) } # transform all values and see if it meets the set threshold checked <- suppressWarnings(as.sir(x)) outcome <- sum(is.na(checked)) / length(x) outcome <= threshold } } #' @export # extra param: warn (logical, to never throw a warning) as.sir.default <- function(x, ...) { if (inherits(x, "sir")) { return(x) } x.bak <- x x <- as.character(x) # this is needed to prevent the vctrs pkg from throwing an error if (inherits(x.bak, c("integer", "numeric", "double")) && all(x %in% c(1:3, NA))) { # support haven package for importing e.g., from SPSS - it adds the 'labels' attribute lbls <- attributes(x.bak)$labels if (!is.null(lbls) && all(c("S", "I", "R") %in% names(lbls)) && all(c(1:3) %in% lbls)) { x[x.bak == 1] <- names(lbls[lbls == 1]) x[x.bak == 2] <- names(lbls[lbls == 2]) x[x.bak == 3] <- names(lbls[lbls == 3]) } else { x[x.bak == 1] <- "S" x[x.bak == 2] <- "I" x[x.bak == 3] <- "R" } } else if (inherits(x.bak, "character") && all(x %in% c("1", "2", "3", "S", "I", "R", NA_character_))) { x[x.bak == "1"] <- "S" x[x.bak == "2"] <- "I" x[x.bak == "3"] <- "R" } else if (!all(is.na(x)) && !identical(levels(x), c("S", "I", "R")) && !all(x %in% c("S", "I", "R", NA))) { if (all(x %unlike% "(R|S|I)", na.rm = TRUE)) { # check if they are actually MICs or disks if (all_valid_mics(x)) { warning_("in `as.sir()`: the input seems to contain MIC values. You can transform them with `as.mic()` before running `as.sir()` to interpret them.") } else if (all_valid_disks(x)) { warning_("in `as.sir()`: the input seems to contain disk diffusion values. You can transform them with `as.disk()` before running `as.sir()` to interpret them.") } } # trim leading and trailing spaces, new lines, etc. x <- trimws2(as.character(unlist(x))) x[x %in% c(NA, "", "-", "NULL")] <- NA_character_ x.bak <- x na_before <- length(x[is.na(x)]) # correct for translations trans_R <- unlist(TRANSLATIONS[ which(TRANSLATIONS$pattern == "Resistant"), 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", "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[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 other invalid characters # set to capitals x <- toupper(x) x <- gsub("[^A-Z]+", "", x, perl = TRUE) # CLSI uses SDD for "susceptible dose-dependent" x <- gsub("SDD", "I", x, fixed = TRUE) # some labs now report "H" instead of "I" to not interfere with EUCAST prior to 2019 x <- gsub("H", "I", x, fixed = TRUE) # MIPS uses D for Dose-dependent (which is I, but it will throw a note) x <- gsub("D", "I", x, fixed = TRUE) # MIPS uses U for "susceptible urine" x <- gsub("U", "S", x, fixed = TRUE) # in cases of "S;S" keep S, but in case of "S;I" make it NA x <- gsub("^S+$", "S", x) x <- gsub("^I+$", "I", x) x <- gsub("^R+$", "R", x) x[!x %in% c("S", "I", "R")] <- NA_character_ na_after <- length(x[is.na(x) | x == ""]) if (!isFALSE(list(...)$warn)) { # so as.sir(..., warn = FALSE) will never throw a warning if (na_before != na_after) { list_missing <- x.bak[is.na(x) & !is.na(x.bak) & x.bak != ""] %pm>% unique() %pm>% sort() %pm>% vector_and(quotes = TRUE) cur_col <- get_current_column() warning_("in `as.sir()`: ", na_after - na_before, " result", ifelse(na_after - na_before > 1, "s", ""), ifelse(is.null(cur_col), "", paste0(" in column '", cur_col, "'")), " truncated (", round(((na_after - na_before) / length(x)) * 100), "%) that were invalid antimicrobial interpretations: ", list_missing, call = FALSE ) } if (any(toupper(x.bak[!is.na(x.bak)]) == "U") && message_not_thrown_before("as.sir", "U")) { warning_("in `as.sir()`: 'U' was interpreted as 'S', following some laboratory systems") } if (any(toupper(x.bak[!is.na(x.bak)]) == "D") && message_not_thrown_before("as.sir", "D")) { warning_("in `as.sir()`: 'D' (dose-dependent) was interpreted as 'I', following some laboratory systems") } if (any(toupper(x.bak[!is.na(x.bak)]) == "SDD") && message_not_thrown_before("as.sir", "SDD")) { warning_("in `as.sir()`: 'SDD' (susceptible dose-dependent, coined by CLSI) was interpreted as 'I' to comply with EUCAST's 'I'") } if (any(toupper(x.bak[!is.na(x.bak)]) == "H") && message_not_thrown_before("as.sir", "H")) { warning_("in `as.sir()`: 'H' was interpreted as 'I', following some laboratory systems") } } } set_clean_class(factor(x, levels = c("S", "I", "R"), ordered = TRUE), new_class = c("sir", "ordered", "factor") ) } #' @rdname as.sir #' @export as.sir.mic <- function(x, mo = NULL, ab = deparse(substitute(x)), guideline = getOption("AMR_guideline", "EUCAST"), uti = NULL, conserve_capped_values = FALSE, add_intrinsic_resistance = FALSE, reference_data = AMR::clinical_breakpoints, include_screening = getOption("AMR_include_screening", FALSE), include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { as_sir_method( method_short = "mic", method_long = "MIC values", x = x, mo = mo, ab = ab, guideline = guideline, uti = uti, conserve_capped_values = conserve_capped_values, add_intrinsic_resistance = add_intrinsic_resistance, reference_data = reference_data, include_screening = include_screening, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) } #' @rdname as.sir #' @export as.sir.disk <- function(x, mo = NULL, ab = deparse(substitute(x)), guideline = getOption("AMR_guideline", "EUCAST"), uti = NULL, add_intrinsic_resistance = FALSE, reference_data = AMR::clinical_breakpoints, include_screening = getOption("AMR_include_screening", FALSE), include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human"), ...) { as_sir_method( method_short = "disk", method_long = "disk diffusion zones", x = x, mo = mo, ab = ab, guideline = guideline, uti = uti, conserve_capped_values = FALSE, add_intrinsic_resistance = add_intrinsic_resistance, reference_data = reference_data, include_screening = include_screening, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, ... ) } #' @rdname as.sir #' @export as.sir.data.frame <- function(x, ..., col_mo = NULL, guideline = getOption("AMR_guideline", "EUCAST"), uti = NULL, conserve_capped_values = FALSE, add_intrinsic_resistance = FALSE, reference_data = AMR::clinical_breakpoints, include_screening = getOption("AMR_include_screening", FALSE), include_PKPD = getOption("AMR_include_PKPD", TRUE), breakpoint_type = getOption("AMR_breakpoint_type", "human")) { meet_criteria(x, allow_class = "data.frame") # will also check for dimensions > 0 meet_criteria(col_mo, allow_class = "character", is_in = colnames(x), allow_NULL = TRUE) meet_criteria(guideline, allow_class = "character", has_length = 1) meet_criteria(uti, allow_class = c("logical", "character"), allow_NULL = TRUE, allow_NA = TRUE) meet_criteria(conserve_capped_values, allow_class = "logical", has_length = 1) meet_criteria(add_intrinsic_resistance, allow_class = "logical", has_length = 1) meet_criteria(reference_data, allow_class = "data.frame") meet_criteria(include_screening, allow_class = "logical", has_length = 1) meet_criteria(include_PKPD, allow_class = "logical", has_length = 1) meet_criteria(breakpoint_type, allow_class = "character", is_in = reference_data$type, has_length = 1) x.bak <- x for (i in seq_len(ncol(x))) { # don't keep factors, overwriting them is hard if (is.factor(x[, i, drop = TRUE])) { x[, i] <- as.character(x[, i, drop = TRUE]) } } # -- MO col_mo.bak <- col_mo if (is.null(col_mo)) { col_mo <- search_type_in_df(x = x, type = "mo", info = FALSE) } # -- UTIs col_uti <- uti if (is.null(col_uti)) { col_uti <- search_type_in_df(x = x, type = "uti") } if (!is.null(col_uti)) { if (is.logical(col_uti)) { # already a [logical] vector as input if (length(col_uti) == 1) { uti <- rep(col_uti, NROW(x)) } else { uti <- col_uti } } else { # column found, transform to logical stop_if( length(col_uti) != 1 | !col_uti %in% colnames(x), "argument `uti` must be a [logical] vector, of must be a single column name of `x`" ) uti <- as.logical(x[, col_uti, drop = TRUE]) } } else { # col_uti is still NULL - look for specimen column and make logicals of the urines col_specimen <- suppressMessages(search_type_in_df(x = x, type = "specimen")) if (!is.null(col_specimen)) { uti <- x[, col_specimen, drop = TRUE] %like% "urin" values <- sort(unique(x[uti, col_specimen, drop = TRUE])) if (length(values) > 1) { plural <- c("s", "", "") } else { plural <- c("", "s", "a ") } message_( "Assuming value", plural[1], " ", vector_and(values, quotes = TRUE), " in column '", font_bold(col_specimen), "' reflect", plural[2], " ", plural[3], "urinary tract infection", plural[1], ".\n Use `as.sir(uti = FALSE)` to prevent this." ) } else { # no data about UTI's found uti <- NULL } } i <- 0 if (tryCatch(length(list(...)) > 0, error = function(e) TRUE)) { sel <- colnames(pm_select(x, ...)) } else { sel <- colnames(x) } if (!is.null(col_mo)) { sel <- sel[sel != col_mo] } ab_cols <- colnames(x)[vapply(FUN.VALUE = logical(1), x, function(y) { i <<- i + 1 check <- is.mic(y) | is.disk(y) ab <- colnames(x)[i] if (!is.null(col_mo) && ab == col_mo) { return(FALSE) } if (!is.null(col_uti) && ab == col_uti) { return(FALSE) } if (length(sel) == 0 || (length(sel) > 0 && ab %in% sel)) { ab_coerced <- suppressWarnings(as.ab(ab)) if (is.na(ab_coerced) || (length(sel) > 0 & !ab %in% sel)) { # not even a valid AB code return(FALSE) } else { return(TRUE) } } else { return(FALSE) } })] stop_if( length(ab_cols) == 0, "no columns with MIC values, disk zones or antibiotic column names found in this data set. Use as.mic() or as.disk() to transform antimicrobial columns." ) # set type per column types <- character(length(ab_cols)) types[vapply(FUN.VALUE = logical(1), x.bak[, ab_cols, drop = FALSE], is.disk)] <- "disk" types[vapply(FUN.VALUE = logical(1), x.bak[, ab_cols, drop = FALSE], is.mic)] <- "mic" types[types == "" & vapply(FUN.VALUE = logical(1), x[, ab_cols, drop = FALSE], all_valid_disks)] <- "disk" types[types == "" & vapply(FUN.VALUE = logical(1), x[, ab_cols, drop = FALSE], all_valid_mics)] <- "mic" types[types == "" & !vapply(FUN.VALUE = logical(1), x.bak[, ab_cols, drop = FALSE], is.sir)] <- "sir" if (any(types %in% c("mic", "disk"), na.rm = TRUE)) { # now we need an mo column stop_if(is.null(col_mo), "`col_mo` must be set") # if not null, we already found it, now find again so a message will show if (is.null(col_mo.bak)) { col_mo <- search_type_in_df(x = x, type = "mo") } x_mo <- as.mo(x[, col_mo, drop = TRUE]) } for (i in seq_len(length(ab_cols))) { if (types[i] == "mic") { x[, ab_cols[i]] <- x %pm>% pm_pull(ab_cols[i]) %pm>% as.character() %pm>% as.mic() %pm>% as.sir( mo = x_mo, mo.bak = x[, col_mo, drop = TRUE], ab = ab_cols[i], guideline = guideline, uti = uti, conserve_capped_values = conserve_capped_values, add_intrinsic_resistance = add_intrinsic_resistance, reference_data = reference_data, include_screening = include_screening, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, is_data.frame = TRUE ) } else if (types[i] == "disk") { x[, ab_cols[i]] <- x %pm>% pm_pull(ab_cols[i]) %pm>% as.character() %pm>% as.disk() %pm>% as.sir( mo = x_mo, mo.bak = x[, col_mo, drop = TRUE], ab = ab_cols[i], guideline = guideline, uti = uti, add_intrinsic_resistance = add_intrinsic_resistance, reference_data = reference_data, include_screening = include_screening, include_PKPD = include_PKPD, breakpoint_type = breakpoint_type, is_data.frame = TRUE ) } else if (types[i] == "sir") { show_message <- FALSE ab <- ab_cols[i] ab_coerced <- suppressWarnings(as.ab(ab)) if (!all(x[, ab_cols[i], drop = TRUE] %in% c("S", "I", "R", NA), na.rm = TRUE)) { show_message <- TRUE # only print message if values are not already clean message_("=> Cleaning values in column '", font_bold(ab), "' (", ifelse(ab_coerced != toupper(ab), paste0(ab_coerced, ", "), ""), ab_name(ab_coerced, tolower = TRUE), ")... ", appendLF = FALSE, as_note = FALSE ) } else if (!is.sir(x.bak[, ab_cols[i], drop = TRUE])) { show_message <- TRUE # only print message if class not already set message_("=> Assigning class 'sir' to already clean column '", font_bold(ab), "' (", ifelse(ab_coerced != toupper(ab), paste0(ab_coerced, ", "), ""), ab_name(ab_coerced, tolower = TRUE, language = NULL), ")... ", appendLF = FALSE, as_note = FALSE ) } x[, ab_cols[i]] <- as.sir.default(x = as.character(x[, ab_cols[i], drop = TRUE])) if (show_message == TRUE) { message_(" OK.", add_fn = list(font_green), as_note = FALSE) } } } x } get_guideline <- function(guideline, reference_data) { if (!identical(reference_data, AMR::clinical_breakpoints)) { return(guideline) } guideline_param <- toupper(guideline) if (guideline_param %in% c("CLSI", "EUCAST")) { guideline_param <- rev(sort(subset(reference_data, guideline %like% guideline_param)$guideline))[1L] } if (guideline_param %unlike% " ") { # like 'EUCAST2020', should be 'EUCAST 2020' guideline_param <- gsub("([a-z]+)([0-9]+)", "\\1 \\2", guideline_param, ignore.case = TRUE) } stop_ifnot(guideline_param %in% reference_data$guideline, "invalid guideline: '", guideline, "'.\nValid guidelines are: ", vector_and(reference_data$guideline, quotes = TRUE, reverse = TRUE), call = FALSE ) guideline_param } as_sir_method <- function(method_short, method_long, x, mo, ab, guideline, uti, conserve_capped_values, add_intrinsic_resistance, reference_data, include_screening, include_PKPD, breakpoint_type, ...) { meet_criteria(x, allow_NA = TRUE, .call_depth = -2) meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE, .call_depth = -2) meet_criteria(ab, allow_class = c("ab", "character"), has_length = 1, .call_depth = -2) meet_criteria(guideline, allow_class = "character", has_length = 1, .call_depth = -2) meet_criteria(uti, allow_class = "logical", has_length = c(1, length(x)), allow_NULL = TRUE, allow_NA = TRUE, .call_depth = -2) meet_criteria(conserve_capped_values, allow_class = "logical", has_length = 1, .call_depth = -2) meet_criteria(add_intrinsic_resistance, allow_class = "logical", has_length = 1, .call_depth = -2) meet_criteria(reference_data, allow_class = "data.frame", .call_depth = -2) meet_criteria(include_screening, allow_class = "logical", has_length = 1, .call_depth = -2) meet_criteria(include_PKPD, allow_class = "logical", has_length = 1, .call_depth = -2) check_reference_data(reference_data, .call_depth = -2) meet_criteria(breakpoint_type, allow_class = "character", is_in = reference_data$type, has_length = 1, .call_depth = -2) guideline_coerced <- get_guideline(guideline, reference_data) if (message_not_thrown_before("as.sir", "sir_interpretation_history")) { message_("Run `sir_interpretation_history()` afterwards to retrieve a logbook with all the details of the breakpoint interpretations. Note that some microorganisms might not have breakpoints for each antimicrobial drug in ", guideline_coerced, ".\n\n") } # for dplyr's across() cur_column_dplyr <- import_fn("cur_column", "dplyr", error_on_fail = FALSE) if (!is.null(cur_column_dplyr) && tryCatch(is.data.frame(get_current_data("ab", call = 0)), error = function(e) FALSE)) { # try to get current column, which will only be available when in across() ab <- tryCatch(cur_column_dplyr(), error = function(e) ab ) } # for auto-determining mo mo_var_found <- "" if (is.null(mo)) { tryCatch( { df <- get_current_data(arg_name = "mo", call = -3) # will return an error if not found mo <- NULL try( { mo <- suppressMessages(search_type_in_df(df, "mo")) }, silent = TRUE ) if (!is.null(df) && !is.null(mo) && is.data.frame(df)) { mo_var_found <- paste0(" based on column '", font_bold(mo), "'") mo <- df[, mo, drop = TRUE] } }, error = function(e) { mo <- NULL } ) } if (is.null(mo)) { stop_("No information was supplied about the microorganisms (missing argument `mo` and no column of class 'mo' found). See ?as.sir.\n\n", "To transform certain columns with e.g. mutate(), use `data %>% mutate(across(..., as.sir, mo = x))`, where x is your column with microorganisms.\n", "To transform all ", method_long, " in a data set, use `data %>% as.sir()` or `data %>% mutate_if(is.", method_short, ", as.sir)`.", call = FALSE ) } if (length(ab) == 1 && ab %like% paste0("as.", method_short)) { stop_("No unambiguous name was supplied about the antibiotic (argument `ab`). See ?as.sir.", call = FALSE) } ab.bak <- ab ab <- suppressWarnings(as.ab(ab)) if (!is.null(list(...)$mo.bak)) { mo.bak <- list(...)$mo.bak } else { mo.bak <- mo } # be sure to take current taxonomy, as the 'clinical_breakpoints' data set only contains current taxonomy mo <- suppressWarnings(suppressMessages(as.mo(mo, keep_synonyms = FALSE, info = FALSE))) if (is.na(ab)) { message_("Returning NAs for unknown antibiotic: '", font_bold(ab.bak), "'. Rename this column to a valid name or code, and check the output with `as.ab()`.", add_fn = font_red, as_note = FALSE ) return(as.sir(rep(NA, length(x)))) } if (length(mo) == 1) { mo <- rep(mo, length(x)) } if (is.null(uti)) { uti <- NA } if (length(uti) == 1) { uti <- rep(uti, length(x)) } if (isTRUE(add_intrinsic_resistance) && guideline_coerced %unlike% "EUCAST") { if (message_not_thrown_before("as.sir", "intrinsic")) { warning_("in `as.sir()`: using 'add_intrinsic_resistance' is only useful when using EUCAST guidelines, since the rules for intrinsic resistance are based on EUCAST.") } } agent_formatted <- paste0("'", font_bold(ab.bak), "'") agent_name <- ab_name(ab, tolower = TRUE, language = NULL) if (generalise_antibiotic_name(ab.bak) == generalise_antibiotic_name(agent_name)) { agent_formatted <- paste0( agent_formatted, " (", ab, ")" ) } else if (generalise_antibiotic_name(ab) != generalise_antibiotic_name(agent_name)) { agent_formatted <- paste0( agent_formatted, " (", ifelse(ab.bak == ab, "", paste0(ab, ", ") ), agent_name, ")" ) } # this intro text will also be printed in the progress bar in the `progress` package is installed intro_txt <- paste0("Interpreting ", method_long, ": ", ifelse(isTRUE(list(...)$is_data.frame), "column ", ""), agent_formatted, mo_var_found, ifelse(identical(reference_data, AMR::clinical_breakpoints), paste0(", ", font_bold(guideline_coerced)), ""), "... ") message_(intro_txt, appendLF = FALSE, as_note = FALSE) msg_note <- function(messages) { messages <- unique(messages) for (i in seq_len(length(messages))) { messages[i] <- word_wrap(extra_indent = 5, messages[i]) } message( font_yellow_bg(paste0(" NOTE", ifelse(length(messages) > 1, "S", ""), " \n")), paste0(" ", font_black(AMR_env$bullet_icon), " ", font_black(messages, collapse = NULL), collapse = "\n") ) } method <- method_short metadata_mo <- get_mo_uncertainties() df <- data.frame( values = x, mo = mo, result = NA_sir_, uti = uti, stringsAsFactors = FALSE ) if (method == "mic") { # when as.sir.mic is called directly df$values <- as.mic(df$values) } else if (method == "disk") { # when as.sir.disk is called directly df$values <- as.disk(df$values) } df_unique <- unique(df[ , c("mo", "uti"), drop = FALSE]) rise_warning <- FALSE rise_note <- FALSE method_coerced <- toupper(method) ab_coerced <- as.ab(ab) if (identical(reference_data, AMR::clinical_breakpoints)) { breakpoints <- reference_data %pm>% subset(guideline == guideline_coerced & method == method_coerced & ab == ab_coerced) if (ab_coerced == "AMX" && nrow(breakpoints) == 0) { ab_coerced <- "AMP" breakpoints <- reference_data %pm>% subset(guideline == guideline_coerced & method == method_coerced & ab == ab_coerced) } } else { breakpoints <- reference_data %pm>% subset(method == method_coerced & ab == ab_coerced) } breakpoints <- breakpoints %pm>% subset(type == breakpoint_type) if (isFALSE(include_screening)) { # remove screening rules from the breakpoints table breakpoints <- breakpoints %pm>% subset(site %unlike% "screen" & ref_tbl %unlike% "screen") } if (isFALSE(include_PKPD)) { # remove PKPD rules from the breakpoints table breakpoints <- breakpoints %pm>% subset(mo != "UNKNOWN" & ref_tbl %unlike% "PK.*PD") } msgs <- character(0) if (nrow(breakpoints) == 0) { # apparently no breakpoints found message( paste0(font_rose_bg(" WARNING "), "\n"), font_black(paste0(" ", AMR_env$bullet_icon, " No ", method_coerced, " breakpoints available for ", suppressMessages(suppressWarnings(ab_name(ab_coerced, language = NULL, tolower = TRUE))), " (", ab_coerced, ")."))) load_mo_uncertainties(metadata_mo) return(rep(NA_sir_, nrow(df))) } if (guideline_coerced %like% "EUCAST") { any_is_intrinsic_resistant <- FALSE add_intrinsic_resistance_to_AMR_env() } p <- progress_ticker(n = nrow(df_unique), n_min = 10, title = font_blue(intro_txt), only_bar_percent = TRUE) has_progress_bar <- !is.null(import_fn("progress_bar", "progress", error_on_fail = FALSE)) && nrow(df_unique) >= 10 on.exit(close(p)) # run the rules for (i in seq_len(nrow(df_unique))) { p$tick() mo_current <- df_unique[i, "mo", drop = TRUE] uti_current <- df_unique[i, "uti", drop = TRUE] if (is.na(uti_current)) { # no preference, so no filter on UTIs rows <- which(df$mo == mo_current) } else { rows <- which(df$mo == mo_current & df$uti == uti_current) } values <- df[rows, "values", drop = TRUE] new_sir <- rep(NA_sir_, length(rows)) # find different mo properties, as fast as possible mo_current_genus <- AMR_env$MO_lookup$mo[match(AMR_env$MO_lookup$genus[match(mo_current, AMR_env$MO_lookup$mo)], AMR_env$MO_lookup$fullname)] mo_current_family <- AMR_env$MO_lookup$mo[match(AMR_env$MO_lookup$family[match(mo_current, AMR_env$MO_lookup$mo)], AMR_env$MO_lookup$fullname)] mo_current_order <- AMR_env$MO_lookup$mo[match(AMR_env$MO_lookup$order[match(mo_current, AMR_env$MO_lookup$mo)], AMR_env$MO_lookup$fullname)] mo_current_class <- AMR_env$MO_lookup$mo[match(AMR_env$MO_lookup$class[match(mo_current, AMR_env$MO_lookup$mo)], AMR_env$MO_lookup$fullname)] mo_current_rank <- AMR_env$MO_lookup$rank[match(mo_current, AMR_env$MO_lookup$mo)] mo_current_name <- AMR_env$MO_lookup$fullname[match(mo_current, AMR_env$MO_lookup$mo)] if (mo_current %in% AMR::microorganisms.groups$mo) { # get the species group (might be more than 1 entry) mo_current_species_group <- AMR::microorganisms.groups$mo_group[which(AMR::microorganisms.groups$mo == mo_current)] } else { mo_current_species_group <- NULL } mo_current_other <- structure("UNKNOWN", class = c("mo", "character")) # formatted for notes mo_formatted <- mo_current_name if (!mo_current_rank %in% c("kingdom", "phylum", "class", "order")) { mo_formatted <- font_italic(mo_formatted) } ab_formatted <- paste0( suppressMessages(suppressWarnings(ab_name(ab_coerced, language = NULL, tolower = TRUE))), " (", ab_coerced, ")" ) # gather all available breakpoints for current MO and sort on taxonomic rank # (this will prefer species breakpoints over order breakpoints) breakpoints_current <- breakpoints %pm>% subset(mo %in% c( mo_current, mo_current_genus, mo_current_family, mo_current_order, mo_current_class, mo_current_species_group, mo_current_other )) if (is.na(unique(uti_current))) { breakpoints_current <- breakpoints_current %pm>% # this will put UTI = FALSE first, then UTI = TRUE, then UTI = NA pm_arrange(rank_index, uti) # 'uti' is a column in data set 'clinical_breakpoints' } else if (unique(uti_current) == TRUE) { breakpoints_current <- breakpoints_current %pm>% subset(uti == TRUE) %pm>% # be as specific as possible (i.e. prefer species over genus): pm_arrange(rank_index) } else if (unique(uti_current) == FALSE) { breakpoints_current <- breakpoints_current %pm>% subset(uti == FALSE) %pm>% # be as specific as possible (i.e. prefer species over genus): pm_arrange(rank_index) } # throw notes for different body sites site <- breakpoints_current[1L, "site", drop = FALSE] # this is the one we'll take if (is.na(site)) { site <- paste0("an unspecified body site") } else { site <- paste0("body site '", site, "'") } if (nrow(breakpoints_current) == 1 && all(breakpoints_current$uti == TRUE) && any(uti_current %in% c(FALSE, NA)) && message_not_thrown_before("as.sir", "uti", ab_coerced)) { # only UTI breakpoints available warning_("in `as.sir()`: interpretation of ", font_bold(ab_formatted), " is only available for (uncomplicated) urinary tract infections (UTI) for some microorganisms, thus assuming `uti = TRUE`. See `?as.sir`.") rise_warning <- TRUE } else if (nrow(breakpoints_current) > 1 && length(unique(breakpoints_current$site)) > 1 && any(is.na(uti_current)) && all(c(TRUE, FALSE) %in% breakpoints_current$uti, na.rm = TRUE) && message_not_thrown_before("as.sir", "siteUTI", mo_current, ab_coerced)) { # both UTI and Non-UTI breakpoints available msgs <- c(msgs, paste0("Breakpoints for UTI ", font_underline("and"), " non-UTI available for ", ab_formatted, " in ", mo_formatted, " - assuming ", site, ". Use argument `uti` to set which isolates are from urine. See `?as.sir`.")) breakpoints_current <- breakpoints_current %pm>% pm_filter(uti == FALSE) } else if (nrow(breakpoints_current) > 1 && length(unique(breakpoints_current$site)) > 1 && all(breakpoints_current$uti == FALSE, na.rm = TRUE) && message_not_thrown_before("as.sir", "siteOther", mo_current, ab_coerced)) { # breakpoints for multiple body sites available msgs <- c(msgs, paste0("Multiple breakpoints available for ", ab_formatted, " in ", mo_formatted, " - assuming ", site, ".")) } else if (nrow(breakpoints_current) == 0) { # # do not note - it's already in the header before the interpretation starts next } # first check if mo is intrinsic resistant if (isTRUE(add_intrinsic_resistance) && guideline_coerced %like% "EUCAST" && paste(mo_current, ab_coerced) %in% AMR_env$intrinsic_resistant) { msgs <- c(msgs, paste0("Intrinsic resistance applied for ", ab_formatted, " in ", mo_formatted, "")) new_sir <- rep(as.sir("R"), length(rows)) } else if (nrow(breakpoints_current) == 0) { # no rules available new_sir <- rep(NA_sir_, length(rows)) } else { # then run the rules breakpoints_current <- breakpoints_current[1L, , drop = FALSE] if (any(breakpoints_current$mo == "UNKNOWN", na.rm = TRUE) | any(breakpoints_current$ref_tbl %like% "PK.*PD", na.rm = TRUE)) { msgs <- c(msgs, "Some PK/PD breakpoints were applied - use `include_PKPD = FALSE` to prevent this") } if (any(breakpoints_current$site %like% "screen", na.rm = TRUE) | any(breakpoints_current$ref_tbl %like% "screen", na.rm = TRUE)) { msgs <- c(msgs, "Some screening breakpoints were applied - use `include_screening = FALSE` to prevent this") } if (method == "mic") { new_sir <- case_when_AMR( is.na(values) ~ NA_sir_, values <= breakpoints_current$breakpoint_S ~ as.sir("S"), guideline_coerced %like% "EUCAST" & values > breakpoints_current$breakpoint_R ~ as.sir("R"), guideline_coerced %like% "CLSI" & values >= breakpoints_current$breakpoint_R ~ as.sir("R"), # return "I" when breakpoints are in the middle !is.na(breakpoints_current$breakpoint_S) & !is.na(breakpoints_current$breakpoint_R) ~ as.sir("I"), # and NA otherwise TRUE ~ NA_sir_ ) } else if (method == "disk") { new_sir <- case_when_AMR( is.na(values) ~ NA_sir_, as.double(values) >= as.double(breakpoints_current$breakpoint_S) ~ as.sir("S"), guideline_coerced %like% "EUCAST" & as.double(values) < as.double(breakpoints_current$breakpoint_R) ~ as.sir("R"), guideline_coerced %like% "CLSI" & as.double(values) <= as.double(breakpoints_current$breakpoint_R) ~ as.sir("R"), # return "I" when breakpoints are in the middle !is.na(breakpoints_current$breakpoint_S) & !is.na(breakpoints_current$breakpoint_R) ~ as.sir("I"), # and NA otherwise TRUE ~ NA_sir_ ) } # write to verbose output AMR_env$sir_interpretation_history <- rbind_AMR( AMR_env$sir_interpretation_history, # recycling 1 to 2 rows does not seem to work, which is why rep() was added data.frame( datetime = rep(Sys.time(), length(rows)), index = rows, ab_user = rep(ab.bak, length(rows)), mo_user = rep(mo.bak[match(mo_current, df$mo)][1], length(rows)), ab = rep(ab_coerced, length(rows)), mo = rep(breakpoints_current[, "mo", drop = TRUE], length(rows)), input = as.double(values), outcome = as.sir(new_sir), method = rep(method_coerced, length(rows)), breakpoint_S_R = rep(paste0(breakpoints_current[, "breakpoint_S", drop = TRUE], "-", breakpoints_current[, "breakpoint_R", drop = TRUE]), length(rows)), guideline = rep(guideline_coerced, length(rows)), ref_table = rep(breakpoints_current[, "ref_tbl", drop = TRUE], length(rows)), uti = rep(breakpoints_current[, "uti", drop = TRUE], length(rows)), stringsAsFactors = FALSE ) ) } df[rows, "result"] <- new_sir } close(p) # printing messages if (has_progress_bar == TRUE) { # the progress bar has overwritten the intro text, so: message_(intro_txt, appendLF = FALSE, as_note = FALSE) } if (isTRUE(rise_warning)) { message(font_rose_bg(" WARNING ")) } else if (length(msgs) == 0) { message(font_green_bg(" OK ")) } else { msg_note(sort(msgs)) } load_mo_uncertainties(metadata_mo) df$result } #' @rdname as.sir #' @param clean a [logical] to indicate whether previously stored results should be forgotten after returning the 'logbook' with results #' @export sir_interpretation_history <- function(clean = FALSE) { meet_criteria(clean, allow_class = "logical", has_length = 1) out <- AMR_env$sir_interpretation_history if (NROW(out) == 0) { message_("No results to return. Run `as.sir()` on MIC values or disk diffusion zones first to see a 'logbook' data set here.") return(invisible(NULL)) } out$outcome <- as.sir(out$outcome) # keep stored for next use if (isTRUE(clean)) { AMR_env$sir_interpretation_history <- AMR_env$sir_interpretation_history[0, , drop = FALSE] } # sort descending on time out <- out[order(out$datetime, decreasing = TRUE), , drop = FALSE] if (pkg_is_available("tibble")) { import_fn("as_tibble", "tibble")(out) } else { out } } # will be exported using s3_register() in R/zzz.R pillar_shaft.sir <- function(x, ...) { out <- trimws(format(x)) if (has_colour()) { # colours will anyway not work when has_colour() == FALSE, # but then the indentation should also not be applied out[is.na(x)] <- font_grey(" NA") out[x == "S"] <- font_green_bg(" S ") out[x == "I"] <- font_orange_bg(" I ") if (is_dark()) { out[x == "R"] <- font_red_bg(" R ") } else { out[x == "R"] <- font_rose_bg(" R ") } } create_pillar_column(out, align = "left", width = 5) } # will be exported using s3_register() in R/zzz.R type_sum.sir <- function(x, ...) { "sir" } # will be exported using s3_register() in R/zzz.R freq.sir <- function(x, ...) { x_name <- deparse(substitute(x)) x_name <- gsub(".*[$]", "", x_name) if (x_name %in% c("x", ".")) { # try again going through system calls x_name <- stats::na.omit(vapply( FUN.VALUE = character(1), sys.calls(), function(call) { call_txt <- as.character(call) ifelse(call_txt[1] %like% "freq$", call_txt[length(call_txt)], character(0)) } ))[1L] } ab <- suppressMessages(suppressWarnings(as.ab(x_name))) digits <- list(...)$digits if (is.null(digits)) { digits <- 2 } if (!is.na(ab)) { cleaner::freq.default( x = x, ..., .add_header = list( Drug = paste0(ab_name(ab, language = NULL), " (", ab, ", ", paste(ab_atc(ab), collapse = "/"), ")"), `Drug group` = ab_group(ab, language = NULL), `%SI` = trimws(percentage(susceptibility(x, minimum = 0, as_percent = FALSE), digits = digits )) ) ) } else { cleaner::freq.default( x = x, ..., .add_header = list( `%SI` = trimws(percentage(susceptibility(x, minimum = 0, as_percent = FALSE), digits = digits )) ) ) } } # will be exported using s3_register() in R/zzz.R get_skimmers.sir <- function(column) { # get the variable name 'skim_variable' name_call <- function(.data) { calls <- sys.calls() frms <- sys.frames() calls_txt <- vapply(calls, function(x) paste(deparse(x), collapse = ""), FUN.VALUE = character(1)) if (any(calls_txt %like% "skim_variable", na.rm = TRUE)) { ind <- which(calls_txt %like% "skim_variable")[1L] vars <- tryCatch(eval(parse(text = ".data$skim_variable$sir"), envir = frms[[ind]]), error = function(e) NULL ) tryCatch(ab_name(as.character(calls[[length(calls)]][[2]]), language = NULL), error = function(e) NA_character_ ) } else { NA_character_ } } skimr::sfl( skim_type = "sir", ab_name = name_call, count_R = count_R, count_S = count_susceptible, count_I = count_I, prop_R = ~ proportion_R(., minimum = 0), prop_S = ~ susceptibility(., minimum = 0), prop_I = ~ proportion_I(., minimum = 0) ) } #' @method print sir #' @export #' @noRd print.sir <- function(x, ...) { cat("Class 'sir'\n") print(as.character(x), quote = FALSE) } #' @method droplevels sir #' @export #' @noRd droplevels.sir <- function(x, exclude = if (any(is.na(levels(x)))) NULL else NA, ...) { x <- droplevels.factor(x, exclude = exclude, ...) class(x) <- c("sir", "ordered", "factor") x } #' @method summary sir #' @export #' @noRd summary.sir <- function(object, ...) { x <- object n <- sum(!is.na(x)) S <- sum(x == "S", na.rm = TRUE) I <- sum(x == "I", na.rm = TRUE) R <- sum(x == "R", na.rm = TRUE) pad <- function(x) { if (is.na(x)) { return("??") } if (x == "0%") { x <- " 0.0%" } if (nchar(x) < 5) { x <- paste0(rep(" ", 5 - nchar(x)), x) } x } value <- c( "Class" = "sir", "%R" = paste0(pad(percentage(R / n, digits = 1)), " (n=", R, ")"), "%SI" = paste0(pad(percentage((S + I) / n, digits = 1)), " (n=", S + I, ")"), "- %S" = paste0(pad(percentage(S / n, digits = 1)), " (n=", S, ")"), "- %I" = paste0(pad(percentage(I / n, digits = 1)), " (n=", I, ")") ) class(value) <- c("summaryDefault", "table") value } #' @method [<- sir #' @export #' @noRd "[<-.sir" <- function(i, j, ..., value) { value <- as.sir(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method [[<- sir #' @export #' @noRd "[[<-.sir" <- function(i, j, ..., value) { value <- as.sir(value) y <- NextMethod() attributes(y) <- attributes(i) y } #' @method c sir #' @export #' @noRd c.sir <- function(...) { as.sir(unlist(lapply(list(...), as.character))) } #' @method unique sir #' @export #' @noRd unique.sir <- function(x, incomparables = FALSE, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } #' @method rep sir #' @export #' @noRd rep.sir <- function(x, ...) { y <- NextMethod() attributes(y) <- attributes(x) y } check_reference_data <- function(reference_data, .call_depth) { if (!identical(reference_data, AMR::clinical_breakpoints)) { class_sir <- vapply(FUN.VALUE = character(1), AMR::clinical_breakpoints, function(x) paste0("<", class(x), ">", collapse = " and ")) class_ref <- vapply(FUN.VALUE = character(1), reference_data, function(x) paste0("<", class(x), ">", collapse = " and ")) if (!all(names(class_sir) == names(class_ref))) { stop_("`reference_data` must have the same column names as the 'clinical_breakpoints' data set.", call = .call_depth) } if (!all(class_sir == class_ref)) { stop_("`reference_data` must be the same structure as the 'clinical_breakpoints' data set. Column '", names(class_ref[class_sir != class_ref][1]), "' is of class ", class_ref[class_sir != class_ref][1], ", but should be of class ", class_sir[class_sir != class_ref][1], ".", call = .call_depth) } } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/sir.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # dots2vars <- function(...) { # this function is to give more informative output about # variable names in count_* and proportion_* functions dots <- substitute(list(...)) dots <- as.character(dots)[2:length(dots)] paste0(dots[dots != "."], collapse = "+") } sir_calc <- function(..., ab_result, minimum = 0, as_percent = FALSE, only_all_tested = FALSE, only_count = FALSE) { meet_criteria(ab_result, allow_class = c("character", "numeric", "integer"), has_length = c(1, 2, 3)) 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) meet_criteria(only_all_tested, allow_class = "logical", has_length = 1) meet_criteria(only_count, allow_class = "logical", has_length = 1) data_vars <- dots2vars(...) dots_df <- switch(1, ... ) if (is.data.frame(dots_df)) { # make sure to remove all other classes like tibbles, data.tables, etc dots_df <- as.data.frame(dots_df, stringsAsFactors = FALSE) } dots <- eval(substitute(alist(...))) stop_if(length(dots) == 0, "no variables selected", call = -2) stop_if("also_single_tested" %in% names(dots), "`also_single_tested` was replaced by `only_all_tested`.\n", "Please read Details in the help page (`?proportion`) as this may have a considerable impact on your analysis.", call = -2 ) ndots <- length(dots) if (is.data.frame(dots_df)) { # data.frame passed with other columns, like: example_isolates %pm>% proportion_S(AMC, GEN) dots <- as.character(dots) # remove first element, it's the data.frame if (length(dots) == 1) { dots <- character(0) } else { dots <- dots[2:length(dots)] } if (length(dots) == 0 || all(dots == "df")) { # for complete data.frames, like example_isolates %pm>% select(AMC, GEN) %pm>% proportion_S() # and the old sir function, which has "df" as name of the first argument x <- dots_df } else { # get dots that are in column names already, and the ones that will be once evaluated using dots_df or global env # this is to support susceptibility(example_isolates, AMC, any_of(some_vector_with_AB_names)) dots <- c( dots[dots %in% colnames(dots_df)], eval(parse(text = dots[!dots %in% colnames(dots_df)]), envir = dots_df, enclos = globalenv()) ) dots_not_exist <- dots[!dots %in% colnames(dots_df)] stop_if(length(dots_not_exist) > 0, "column(s) not found: ", vector_and(dots_not_exist, quotes = TRUE), call = -2) x <- dots_df[, dots, drop = FALSE] } } else if (ndots == 1) { # only 1 variable passed (can also be data.frame), like: proportion_S(example_isolates$AMC) and example_isolates$AMC %pm>% proportion_S() x <- dots_df } else { # multiple variables passed without pipe, like: proportion_S(example_isolates$AMC, example_isolates$GEN) x <- NULL try(x <- as.data.frame(dots, stringsAsFactors = FALSE), silent = TRUE) if (is.null(x)) { # support for example_isolates %pm>% group_by(ward) %pm>% summarise(amox = susceptibility(GEN, AMX)) x <- as.data.frame(list(...), stringsAsFactors = FALSE) } } if (is.null(x)) { warning_("argument is NULL (check if columns exist): returning NA") if (as_percent == TRUE) { return(NA_character_) } else { return(NA_real_) } } print_warning <- FALSE ab_result <- as.sir(ab_result) if (is.data.frame(x)) { sir_integrity_check <- character(0) for (i in seq_len(ncol(x))) { # check integrity of columns: force 'sir' class if (!is.sir(x[, i, drop = TRUE])) { sir_integrity_check <- c(sir_integrity_check, as.character(x[, i, drop = TRUE])) x[, i] <- suppressWarnings(as.sir(x[, i, drop = TRUE])) # warning will be given later print_warning <- TRUE } } if (length(sir_integrity_check) > 0) { # 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.integer), stringsAsFactors = FALSE), MARGIN = 1, FUN = min ) numerator <- sum(as.integer(y) %in% as.integer(ab_result), na.rm = TRUE) denominator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) !(anyNA(y)))) } else { # may contain NAs in any column other_values <- setdiff(c(NA, levels(ab_result)), ab_result) 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)))) } } else { # x is not a data.frame if (!is.sir(x)) { x <- as.sir(x) print_warning <- TRUE } numerator <- sum(x %in% ab_result, na.rm = TRUE) denominator <- sum(x %in% levels(ab_result), na.rm = TRUE) } if (print_warning == TRUE) { if (message_not_thrown_before("sir_calc")) { warning_("Increase speed by transforming to class 'sir' on beforehand:\n", " your_data %>% mutate_if(is_sir_eligible, as.sir)", call = FALSE ) } } if (only_count == TRUE) { return(numerator) } if (denominator < minimum) { if (data_vars != "") { data_vars <- paste(" for", data_vars) # also add group name if used in dplyr::group_by() cur_group <- import_fn("cur_group", "dplyr", error_on_fail = FALSE) if (!is.null(cur_group)) { group_df <- tryCatch(cur_group(), error = function(e) data.frame()) if (NCOL(group_df) > 0) { # transform factors to characters group <- vapply(FUN.VALUE = character(1), group_df, function(x) { if (is.numeric(x)) { format(x) } else if (is.logical(x)) { as.character(x) } else { paste0('"', x, '"') } }) data_vars <- paste0(data_vars, " in group: ", paste0(names(group), " = ", group, collapse = ", ")) } } } warning_("Introducing NA: ", ifelse(denominator == 0, "no", paste("only", denominator)), " results available", data_vars, " (`minimum` = ", minimum, ").", call = FALSE ) fraction <- NA_real_ } else { fraction <- numerator / denominator fraction[is.nan(fraction)] <- NA_real_ } if (as_percent == TRUE) { percentage(fraction, digits = 1) } else { fraction } } sir_calc_df <- function(type, # "proportion", "count" or "both" data, translate_ab = "name", language = get_AMR_locale(), minimum = 30, as_percent = FALSE, combine_SI = TRUE, confidence_level = 0.95) { meet_criteria(type, is_in = c("proportion", "count", "both"), has_length = 1) meet_criteria(data, allow_class = "data.frame", contains_column_class = c("sir", "rsi")) meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE) language <- validate_language(language) 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) meet_criteria(combine_SI, allow_class = "logical", has_length = 1) meet_criteria(confidence_level, allow_class = "numeric", has_length = 1) translate_ab <- get_translate_ab(translate_ab) data.bak <- data # select only groups and antibiotics if (is_null_or_grouped_tbl(data)) { data_has_groups <- TRUE groups <- get_group_names(data) data <- data[, c(groups, colnames(data)[vapply(FUN.VALUE = logical(1), data, is.sir)]), drop = FALSE] } else { data_has_groups <- FALSE data <- data[, colnames(data)[vapply(FUN.VALUE = logical(1), data, is.sir)], drop = FALSE] } data <- as.data.frame(data, stringsAsFactors = FALSE) if (isTRUE(combine_SI)) { for (i in seq_len(ncol(data))) { if (is.sir(data[, i, drop = TRUE])) { data[, i] <- as.character(data[, i, drop = TRUE]) data[, i] <- gsub("(I|S)", "SI", data[, i, drop = TRUE]) } } } sum_it <- function(.data) { out <- data.frame( antibiotic = character(0), interpretation = character(0), value = double(0), ci_min = double(0), ci_max = double(0), isolates = integer(0), stringsAsFactors = FALSE ) if (data_has_groups) { group_values <- unique(.data[, which(colnames(.data) %in% groups), drop = FALSE]) rownames(group_values) <- NULL .data <- .data[, which(!colnames(.data) %in% groups), drop = FALSE] } for (i in seq_len(ncol(.data))) { values <- .data[, i, drop = TRUE] if (isTRUE(combine_SI)) { values <- factor(values, levels = c("SI", "R"), ordered = TRUE) } else { values <- factor(values, levels = c("S", "I", "R"), ordered = TRUE) } col_results <- as.data.frame(as.matrix(table(values)), stringsAsFactors = FALSE) col_results$interpretation <- rownames(col_results) col_results$isolates <- col_results[, 1, drop = TRUE] if (NROW(col_results) > 0 && sum(col_results$isolates, na.rm = TRUE) > 0) { if (sum(col_results$isolates, na.rm = TRUE) >= minimum) { col_results$value <- col_results$isolates / sum(col_results$isolates, na.rm = TRUE) ci <- lapply( col_results$isolates, function(x) { stats::binom.test( x = x, n = sum(col_results$isolates, na.rm = TRUE), conf.level = confidence_level )$conf.int } ) col_results$ci_min <- vapply(FUN.VALUE = double(1), ci, `[`, 1) col_results$ci_max <- vapply(FUN.VALUE = double(1), ci, `[`, 2) } else { col_results$value <- rep(NA_real_, NROW(col_results)) # confidence intervals also to NA col_results$ci_min <- col_results$value col_results$ci_max <- col_results$value } out_new <- data.frame( antibiotic = ifelse(isFALSE(translate_ab), colnames(.data)[i], ab_property(colnames(.data)[i], property = translate_ab, language = language) ), interpretation = col_results$interpretation, value = col_results$value, ci_min = col_results$ci_min, ci_max = col_results$ci_max, isolates = col_results$isolates, stringsAsFactors = FALSE ) if (data_has_groups) { if (nrow(group_values) < nrow(out_new)) { # repeat group_values for the number of rows in out_new repeated <- rep(seq_len(nrow(group_values)), each = nrow(out_new) / nrow(group_values) ) group_values <- group_values[repeated, , drop = FALSE] } out_new <- cbind(group_values, out_new) } out <- rbind_AMR(out, out_new) } } out } # based on pm_apply_grouped_function apply_group <- function(.data, fn, groups, drop = FALSE, ...) { grouped <- pm_split_into_groups(.data, groups, drop) res <- do.call(rbind_AMR, unname(lapply(grouped, fn, ...))) if (any(groups %in% colnames(res))) { class(res) <- c("grouped_data", class(res)) res <- pm_set_groups(res, groups[groups %in% colnames(res)]) } res } if (data_has_groups) { out <- apply_group(data, "sum_it", groups) } else { out <- sum_it(data) } # apply factors for right sorting in interpretation if (isTRUE(combine_SI)) { out$interpretation <- factor(out$interpretation, levels = c("SI", "R"), ordered = TRUE) } else { # don't use as.sir() here, as it would add the class 'sir' and we would like # the same data structure as output, regardless of input out$interpretation <- factor(out$interpretation, levels = c("S", "I", "R"), ordered = TRUE) } if (data_has_groups) { # ordering by the groups and two more: "antibiotic" and "interpretation" out <- pm_ungroup(out[do.call("order", out[, seq_len(length(groups) + 2), drop = FALSE]), , drop = FALSE]) } else { out <- out[order(out$antibiotic, out$interpretation), , drop = FALSE] } if (type == "proportion") { # remove number of isolates out <- subset(out, select = -c(isolates)) } else if (type == "count") { # set value to be number of isolates out$value <- out$isolates # remove redundant columns out <- subset(out, select = -c(ci_min, ci_max, isolates)) } rownames(out) <- NULL out <- as_original_data_class(out, class(data.bak)) # will remove tibble groups structure(out, class = c("sir_df", "rsi_df", class(out))) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/sir_calc.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' @rdname proportion #' @export sir_df <- function(data, translate_ab = "name", language = get_AMR_locale(), minimum = 30, as_percent = FALSE, combine_SI = TRUE, confidence_level = 0.95) { tryCatch( sir_calc_df( type = "both", data = data, translate_ab = translate_ab, language = language, minimum = minimum, as_percent = as_percent, combine_SI = combine_SI, confidence_level = confidence_level ), error = function(e) stop_(gsub("in sir_calc_df(): ", "", e$message, fixed = TRUE), call = -5) ) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/sir_df.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Skewness of the Sample #' #' @description Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean. #' #' When negative ('left-skewed'): the left tail is longer; the mass of the distribution is concentrated on the right of a histogram. When positive ('right-skewed'): the right tail is longer; the mass of the distribution is concentrated on the left of a histogram. A normal distribution has a skewness of 0. #' @param x a vector of values, a [matrix] or a [data.frame] #' @param na.rm a [logical] value indicating whether `NA` values should be stripped before the computation proceeds #' @seealso [kurtosis()] #' @rdname skewness #' @export #' @examples #' skewness(runif(1000)) skewness <- function(x, na.rm = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) UseMethod("skewness") } #' @method skewness default #' @rdname skewness #' @export skewness.default <- function(x, na.rm = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) x <- as.vector(x) if (isTRUE(na.rm)) { x <- x[!is.na(x)] } n <- length(x) (sum((x - mean(x))^3) / n) / (sum((x - mean(x))^2) / n)^(3 / 2) } #' @method skewness matrix #' @rdname skewness #' @export skewness.matrix <- function(x, na.rm = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) apply(x, 2, skewness.default, na.rm = na.rm) } #' @method skewness data.frame #' @rdname skewness #' @export skewness.data.frame <- function(x, na.rm = FALSE) { meet_criteria(na.rm, allow_class = "logical", has_length = 1) vapply(FUN.VALUE = double(1), x, skewness.default, na.rm = na.rm) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/skewness.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Translate Strings from the AMR Package #' #' For language-dependent output of `AMR` functions, such as [mo_name()], [mo_gramstain()], [mo_type()] and [ab_name()]. #' @param x text to translate #' @param language language to choose. Use one of these supported language names or ISO-639-1 codes: `r vector_or(paste0(sapply(LANGUAGES_SUPPORTED_NAMES, function(x) x[[1]]), " (" , LANGUAGES_SUPPORTED, ")"), quotes = FALSE, sort = FALSE)`. #' @details The currently `r length(LANGUAGES_SUPPORTED)` supported languages are `r vector_and(paste0(sapply(LANGUAGES_SUPPORTED_NAMES, function(x) x[[1]]), " (" , LANGUAGES_SUPPORTED, ")"), quotes = FALSE, sort = FALSE)`. All these languages have translations available for all antimicrobial drugs and colloquial microorganism names. #' #' To permanently silence the once-per-session language note on a non-English operating system, you can set the [package option][AMR-options] [`AMR_locale`][AMR-options] in your `.Rprofile` file like this: #' #' ```r #' # Open .Rprofile file #' utils::file.edit("~/.Rprofile") #' #' # Then add e.g. Italian support to that file using: #' options(AMR_locale = "Italian") #' ``` #' #' And then save the file. #' #' Please read about adding or updating a language in [our Wiki](https://github.com/msberends/AMR/wiki/). #' #' ### Changing the Default Language #' The system language will be used at default (as returned by `Sys.getenv("LANG")` or, if `LANG` is not set, [`Sys.getlocale("LC_COLLATE")`][Sys.getlocale()]), if that language is supported. But the language to be used can be overwritten in two ways and will be checked in this order: #' #' 1. Setting the [package option][AMR-options] [`AMR_locale`][AMR-options], either by using e.g. `set_AMR_locale("German")` or by running e.g. `options(AMR_locale = "German")`. #' #' Note that setting an \R option only works in the same session. Save the command `options(AMR_locale = "(your language)")` to your `.Rprofile` file to apply it for every session. Run `utils::file.edit("~/.Rprofile")` to edit your `.Rprofile` file. #' 2. Setting the system variable `LANGUAGE` or `LANG`, e.g. by adding `LANGUAGE="de_DE.utf8"` to your `.Renviron` file in your home directory. #' #' Thus, if the [package option][AMR-options] [`AMR_locale`][AMR-options] is set, the system variables `LANGUAGE` and `LANG` will be ignored. #' @rdname translate #' @name translate #' @export #' @examples #' # Current settings (based on system language) #' ab_name("Ciprofloxacin") #' mo_name("Coagulase-negative Staphylococcus (CoNS)") #' #' # setting another language #' set_AMR_locale("Dutch") #' ab_name("Ciprofloxacin") #' mo_name("Coagulase-negative Staphylococcus (CoNS)") #' #' # setting yet another language #' set_AMR_locale("German") #' ab_name("Ciprofloxacin") #' mo_name("Coagulase-negative Staphylococcus (CoNS)") #' #' # set_AMR_locale() understands endonyms, English exonyms, and ISO-639-1: #' set_AMR_locale("Deutsch") #' set_AMR_locale("German") #' set_AMR_locale("de") #' ab_name("amox/clav") #' #' # reset to system default #' reset_AMR_locale() #' ab_name("amox/clav") get_AMR_locale <- function() { # a message for this will be thrown in translate_into_language() if outcome is non-English if (!is.null(getOption("AMR_locale"))) { return(validate_language(getOption("AMR_locale"), extra_txt = "set with `options(AMR_locale = ...)`")) } lang <- "" # now check the LANGUAGE system variable - return it if set if (!identical("", Sys.getenv("LANGUAGE"))) { lang <- Sys.getenv("LANGUAGE") } if (!identical("", Sys.getenv("LANG"))) { lang <- Sys.getenv("LANG") } if (lang == "") { lang <- Sys.getlocale("LC_COLLATE") } find_language(lang) } #' @rdname translate #' @export set_AMR_locale <- function(language) { language <- validate_language(language) options(AMR_locale = language) if (interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")) { # show which language to use now message_( "Using ", LANGUAGES_SUPPORTED_NAMES[[language]]$exonym, ifelse(language != "en", paste0(" (", LANGUAGES_SUPPORTED_NAMES[[language]]$endonym, ")"), "" ), " for the AMR package for this session." ) } } #' @rdname translate #' @export reset_AMR_locale <- function() { options(AMR_locale = NULL) if (interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")) { # show which language to use now language <- suppressMessages(get_AMR_locale()) message_("Using the ", LANGUAGES_SUPPORTED_NAMES[[language]]$exonym, " language (", LANGUAGES_SUPPORTED_NAMES[[language]]$endonym, ") for the AMR package for this session.") } } #' @rdname translate #' @export translate_AMR <- function(x, language = get_AMR_locale()) { translate_into_language(x, language = language, only_unknown = FALSE, only_affect_ab_names = FALSE, only_affect_mo_names = FALSE ) } validate_language <- function(language, extra_txt = character(0)) { if (length(language) == 0 || isTRUE(trimws2(tolower(language[1])) %in% c("en", "english", "", "false", NA))) { return("en") } else if (language[1] %in% LANGUAGES_SUPPORTED) { return(language[1]) } lang <- find_language(language[1], fallback = FALSE) stop_ifnot(length(lang) > 0 && lang %in% LANGUAGES_SUPPORTED, "unsupported language for AMR package", extra_txt, ": \"", language, "\". Use one of these language names or ISO-639-1 codes: ", paste0('"', vapply(FUN.VALUE = character(1), LANGUAGES_SUPPORTED_NAMES, function(x) x[[1]]), '" ("', LANGUAGES_SUPPORTED, '")', collapse = ", " ), call = FALSE ) lang } find_language <- function(language, fallback = TRUE) { language <- Map(LANGUAGES_SUPPORTED_NAMES, LANGUAGES_SUPPORTED, f = function(l, n, check = language) { grepl( paste0( "^(", l[1], "|", l[2], "|", n, "(_|$)|", toupper(n), "(_|$))" ), check, ignore.case = TRUE, perl = TRUE, useBytes = FALSE ) }, USE.NAMES = TRUE ) language <- names(which(language == TRUE)) if (isTRUE(fallback) && length(language) == 0) { # other language -> set to English language <- "en" } language } # translate strings based on inst/translations.tsv translate_into_language <- function(from, language = get_AMR_locale(), only_unknown = FALSE, only_affect_ab_names = FALSE, only_affect_mo_names = FALSE) { # get ISO-639-1 of language lang <- validate_language(language) if (lang == "en") { # don' translate return(from) } df_trans <- TRANSLATIONS # internal data file from.bak <- from from_unique <- unique(from) from_unique_translated <- from_unique # only keep lines where translation is available for this language df_trans <- df_trans[which(!is.na(df_trans[, lang, drop = TRUE])), , drop = FALSE] # and where the original string is not equal to the string in the target language df_trans <- df_trans[which(df_trans[, "pattern", drop = TRUE] != df_trans[, lang, drop = TRUE]), , drop = FALSE] if (only_unknown == TRUE) { df_trans <- subset(df_trans, pattern %like% "unknown") } if (only_affect_ab_names == TRUE) { df_trans <- subset(df_trans, affect_ab_name == TRUE) } if (only_affect_mo_names == TRUE) { df_trans <- subset(df_trans, affect_mo_name == TRUE) } if (NROW(df_trans) == 0) { return(from) } # default: case sensitive if value if 'case_sensitive' is missing: df_trans$case_sensitive[is.na(df_trans$case_sensitive)] <- TRUE # default: not using regular expressions if 'regular_expr' is missing: df_trans$regular_expr[is.na(df_trans$regular_expr)] <- FALSE # check if text to look for is in one of the patterns any_form_in_patterns <- tryCatch( any(from_unique %like% paste0("(", paste(gsub(" +\\(.*", "", df_trans$pattern), collapse = "|"), ")")), error = function(e) { warning_("Translation not possible. Please create an issue at ", font_url("https://github.com/msberends/AMR/issues"), ". Many thanks!") return(FALSE) } ) if (NROW(df_trans) == 0 | !any_form_in_patterns) { return(from) } lapply( # starting with longest pattern, since more general translations are shorter, such as 'Group' order(nchar(df_trans$pattern), decreasing = TRUE), function(i) { from_unique_translated <<- gsub( pattern = df_trans$pattern[i], replacement = df_trans[i, lang, drop = TRUE], x = from_unique_translated, ignore.case = !df_trans$case_sensitive[i] & df_trans$regular_expr[i], fixed = !df_trans$regular_expr[i], perl = df_trans$regular_expr[i] ) } ) # force UTF-8 for diacritics from_unique_translated <- enc2utf8(from_unique_translated) # a kind of left join to get all results back out <- from_unique_translated[match(from.bak, from_unique)] if (!identical(from.bak, out) && get_AMR_locale() == lang && is.null(getOption("AMR_locale", default = NULL)) && message_not_thrown_before("translation", entire_session = TRUE) && interactive()) { message(word_wrap( "Assuming the ", LANGUAGES_SUPPORTED_NAMES[[lang]]$exonym, " language (", LANGUAGES_SUPPORTED_NAMES[[lang]]$endonym, ") for the AMR package. See `set_AMR_locale()` to change this or to silence this once-per-session note.", add_fn = list(font_blue), as_note = TRUE )) } out }
/scratch/gouwar.j/cran-all/cranData/AMR/R/translate.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://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. # see https://github.com/tidyverse/dplyr/issues/5955 why this is required # S3: ab_selector 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) } # S3: ab_selector_any_all vec_ptype2.logical.ab_selector_any_all <- function(x, y, ...) { x } vec_ptype2.ab_selector_any_all.logical <- function(x, y, ...) { y } vec_cast.logical.ab_selector_any_all <- function(x, to, ...) { unclass(x) } # 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, ...) { as.character(x) } vec_cast.ab.character <- function(x, to, ...) { return_after_integrity_check(x, "antimicrobial drug code", as.character(AMR_env$AB_lookup$ab)) } # S3: av vec_ptype2.character.av <- function(x, y, ...) { x } vec_ptype2.av.character <- function(x, y, ...) { y } vec_cast.character.av <- function(x, to, ...) { as.character(x) } vec_cast.av.character <- function(x, to, ...) { return_after_integrity_check(x, "antiviral drug code", as.character(AMR_env$AV_lookup$av)) } # 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, ...) { as.character(x) } vec_cast.mo.character <- function(x, to, ...) { add_MO_lookup_to_AMR_env() return_after_integrity_check(x, "microorganism code", as.character(AMR_env$MO_lookup$mo)) } # 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) } vec_cast.disk.integer <- function(x, to, ...) { as.disk(x) } vec_cast.double.disk <- function(x, to, ...) { unclass(x) } vec_cast.disk.double <- function(x, to, ...) { as.disk(x) } vec_cast.character.disk <- function(x, to, ...) { unclass(x) } vec_cast.disk.character <- function(x, to, ...) { as.disk(x) } # S3: mic vec_cast.character.mic <- function(x, to, ...) { as.character(x) } vec_cast.double.mic <- function(x, to, ...) { as.double(x) } vec_cast.mic.double <- function(x, to, ...) { as.mic(x) } vec_cast.mic.character <- function(x, to, ...) { as.mic(x) } vec_math.mic <- function(.fn, x, ...) { .fn(as.double(x), ...) } # S3: sir vec_ptype2.character.sir <- function(x, y, ...) { x } vec_ptype2.sir.character <- function(x, y, ...) { y } vec_cast.character.sir <- function(x, to, ...) { as.character(x) } vec_cast.sir.character <- function(x, to, ...) { as.sir(x) }
/scratch/gouwar.j/cran-all/cranData/AMR/R/vctrs.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' WHOCC: WHO Collaborating Centre for Drug Statistics Methodology #' #' All antimicrobial drugs and their official names, ATC codes, ATC groups and defined daily dose (DDD) are included in this package, using the WHO Collaborating Centre for Drug Statistics Methodology. #' @section WHOCC: #' This package contains **all ~550 antibiotic, antimycotic and antiviral drugs** and their Anatomical Therapeutic Chemical (ATC) codes, ATC groups and Defined Daily Dose (DDD) from the World Health Organization Collaborating Centre for Drug Statistics Methodology (WHOCC, <https://www.whocc.no>) and the Pharmaceuticals Community Register of the European Commission (<https://ec.europa.eu/health/documents/community-register/html/reg_hum_atc.htm>). #' #' These have become the gold standard for international drug utilisation monitoring and research. #' #' The WHOCC is located in Oslo at the Norwegian Institute of Public Health and funded by the Norwegian government. The European Commission is the executive of the European Union and promotes its general interest. #' #' **NOTE: The WHOCC copyright does not allow use for commercial purposes, unlike any other info from this package.** See <https://www.whocc.no/copyright_disclaimer/.> #' @name WHOCC #' @rdname WHOCC #' @examples #' as.ab("meropenem") #' ab_name("J01DH02") #' #' ab_tradenames("flucloxacillin") NULL
/scratch/gouwar.j/cran-all/cranData/AMR/R/whocc.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # #' Deprecated Functions #' #' These functions are so-called '[Deprecated]'. **They will be removed in a future release.** Using the functions will give a warning with the name of the function it has been replaced by (if there is one). #' @keywords internal #' @name AMR-deprecated #' @rdname AMR-deprecated #' @export NA_rsi_ <- set_clean_class(factor(NA_character_, levels = c("S", "I", "R"), ordered = TRUE), new_class = c("rsi", "ordered", "factor") ) #' @rdname AMR-deprecated #' @export as.rsi <- function(x, ...) { deprecation_warning("as.rsi", "as.sir") UseMethod("as.rsi") } #' @noRd #' @export as.rsi.default <- function(...) { as.sir.default(...) } #' @noRd #' @export as.rsi.mic <- function(...) { as.sir.mic(...) } #' @noRd #' @export as.rsi.disk <- function(...) { as.sir.disk(...) } #' @noRd #' @export as.rsi.data.frame <- function(...) { as.sir.data.frame(...) } #' @rdname AMR-deprecated #' @export facet_rsi <- function(...) { deprecation_warning("facet_rsi", "facet_sir") facet_sir(...) } #' @rdname AMR-deprecated #' @export geom_rsi <- function(...) { deprecation_warning("geom_rsi", "geom_sir") geom_sir(...) } #' @rdname AMR-deprecated #' @export ggplot_rsi <- function(...) { deprecation_warning("ggplot_rsi", "ggplot_sir") ggplot_sir(...) } #' @rdname AMR-deprecated #' @export ggplot_rsi_predict <- function(...) { deprecation_warning("ggplot_rsi_predict", "ggplot_sir_predict") ggplot_sir_predict(...) } #' @rdname AMR-deprecated #' @export is.rsi <- function(...) { # REMINDER: change as.sir() to remove the deprecation warning there suppressWarnings(is.sir(...)) } #' @rdname AMR-deprecated #' @export is.rsi.eligible <- function(...) { deprecation_warning("is.rsi.eligible", "is_sir_eligible") is_sir_eligible(...) } #' @rdname AMR-deprecated #' @export labels_rsi_count <- function(...) { deprecation_warning("labels_rsi_count", "labels_sir_count") labels_sir_count(...) } #' @rdname AMR-deprecated #' @export n_rsi <- function(...) { deprecation_warning("n_rsi", "n_sir") n_sir(...) } #' @rdname AMR-deprecated #' @export random_rsi <- function(...) { deprecation_warning("random_rsi", "random_sir") random_sir(...) } #' @rdname AMR-deprecated #' @export rsi_df <- function(...) { deprecation_warning("rsi_df", "sir_df") sir_df(...) } #' @rdname AMR-deprecated #' @export rsi_predict <- function(...) { deprecation_warning("rsi_predict", "sir_predict") sir_predict(...) } #' @rdname AMR-deprecated #' @export scale_rsi_colours <- function(...) { deprecation_warning("scale_rsi_colours", "scale_sir_colours") scale_sir_colours(...) } #' @rdname AMR-deprecated #' @export theme_rsi <- function(...) { deprecation_warning("theme_rsi", "theme_sir") theme_sir(...) } # will be exported using s3_register() in R/zzz.R pillar_shaft.rsi <- pillar_shaft.sir type_sum.rsi <- function(x, ...) { if (message_not_thrown_before("type_sum.rsi")) { deprecation_warning(extra_msg = "The 'rsi' class has been replaced with 'sir'. Transform your 'rsi' columns to 'sir' with `as.sir()`, e.g.:\n your_data %>% mutate_if(is.rsi, as.sir)") } "rsi" } #' @method print rsi #' @export #' @noRd print.rsi <- function(x, ...) { deprecation_warning(extra_msg = "The 'rsi' class has been replaced with 'sir' - transform your 'rsi' data with `as.sir()`") cat("Class 'rsi'", font_bold(font_red("[!]\n"))) print(as.character(x), quote = FALSE) } #' @noRd #' @export `[<-.rsi` <- `[<-.sir` #' @noRd #' @export `[[<-.rsi` <- `[[<-.sir` #' @noRd #' @export barplot.rsi <- barplot.sir #' @noRd #' @export c.rsi <- c.sir #' @noRd #' @export droplevels.rsi <- droplevels.sir #' @noRd #' @export plot.rsi <- plot.sir #' @noRd #' @export rep.rsi <- rep.sir #' @noRd #' @export summary.rsi <- summary.sir #' @noRd #' @export unique.rsi <- unique.sir # WHEN REMOVING RSI, DON'T FORGET TO REMOVE : # - THE "rsi_df" CLASS FROM R/sir_calc.R # - CODE CONTAINING only_rsi_columns, colours_RSI, include_untested_rsi, prob_RSI deprecation_warning <- function(old = NULL, new = NULL, extra_msg = NULL, is_function = TRUE) { if (is.null(old)) { warning_(extra_msg) } else { env <- paste0("deprecated_", old) if (!env %in% names(AMR_env)) { AMR_env[[paste0("deprecated_", old)]] <- 1 if (isTRUE(is_function)) { old <- paste0(old, "()") new <- paste0(new, "()") type <- "function" } else { type <- "argument" } warning_( ifelse(is.null(new), paste0("The `", old, "` ", type, " is no longer in use"), paste0("The `", old, "` ", type, " has been replaced with `", new, "`") ), ifelse(type == "argument", ". While the old argument still works, it will be removed in a future version, so please update your code.", ", see `?AMR-deprecated`." ), ifelse(!is.null(extra_msg), paste0(" ", extra_msg), "" ), "\nThis warning will be shown once per session." ) } } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/zz_deprecated.R
# ==================================================================== # # 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, Sinha BNM, Albers CJ, Glasner C # # (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://msberends.github.io/AMR/ # # ==================================================================== # # set up package environment, used by numerous AMR functions AMR_env <- new.env(hash = FALSE) AMR_env$mo_uncertainties <- data.frame( original_input = character(0), input = character(0), fullname = character(0), mo = character(0), candidates = character(0), minimum_matching_score = integer(0), keep_synonyms = logical(0), stringsAsFactors = FALSE ) AMR_env$mo_renamed <- list() AMR_env$mo_previously_coerced <- data.frame( x = character(0), mo = character(0), stringsAsFactors = FALSE ) AMR_env$ab_previously_coerced <- data.frame( x = character(0), ab = character(0), stringsAsFactors = FALSE ) AMR_env$av_previously_coerced <- data.frame( x = character(0), av = character(0), stringsAsFactors = FALSE ) AMR_env$sir_interpretation_history <- data.frame( datetime = Sys.time()[0], index = integer(0), ab_user = character(0), mo_user = character(0), ab = set_clean_class(character(0), c("ab", "character")), mo = set_clean_class(character(0), c("mo", "character")), input = double(0), outcome = NA_sir_[0], method = character(0), breakpoint_S_R = character(0), guideline = character(0), ref_table = character(0), stringsAsFactors = FALSE ) AMR_env$custom_ab_codes <- character(0) AMR_env$custom_mo_codes <- character(0) AMR_env$is_dark_theme <- 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) # determine info icon for messages if (pkg_is_available("cli")) { # let cli do the determination of supported symbols AMR_env$info_icon <- import_fn("symbol", "cli")$info AMR_env$bullet_icon <- import_fn("symbol", "cli")$bullet AMR_env$dots <- import_fn("symbol", "cli")$ellipsis } else { AMR_env$info_icon <- "i" AMR_env$bullet_icon <- "*" AMR_env$dots <- "..." } .onLoad <- function(lib, pkg) { # Support for tibble headers (type_sum) and tibble columns content (pillar_shaft) # without the need to depend on other packages. This was suggested by the # developers of the vctrs package: # https://github.com/r-lib/vctrs/blob/05968ce8e669f73213e3e894b5f4424af4f46316/R/register-s3.R s3_register("pillar::pillar_shaft", "ab") s3_register("pillar::pillar_shaft", "av") s3_register("pillar::pillar_shaft", "mo") s3_register("pillar::pillar_shaft", "sir") s3_register("pillar::pillar_shaft", "rsi") # remove in a later version s3_register("pillar::pillar_shaft", "mic") s3_register("pillar::pillar_shaft", "disk") s3_register("pillar::type_sum", "ab") s3_register("pillar::type_sum", "av") s3_register("pillar::type_sum", "mo") s3_register("pillar::type_sum", "sir") s3_register("pillar::type_sum", "rsi") # remove in a later version s3_register("pillar::type_sum", "mic") s3_register("pillar::type_sum", "disk") # Support for frequency tables from the cleaner package s3_register("cleaner::freq", "mo") s3_register("cleaner::freq", "sir") # Support for skim() from the skimr package if (pkg_is_available("skimr", min_version = "2.0.0")) { s3_register("skimr::get_skimmers", "mo") s3_register("skimr::get_skimmers", "sir") s3_register("skimr::get_skimmers", "mic") s3_register("skimr::get_skimmers", "disk") } # Support for autoplot() from the ggplot2 package s3_register("ggplot2::autoplot", "sir") s3_register("ggplot2::autoplot", "mic") s3_register("ggplot2::autoplot", "disk") s3_register("ggplot2::autoplot", "resistance_predict") s3_register("ggplot2::autoplot", "antibiogram") # Support for fortify from the ggplot2 package s3_register("ggplot2::fortify", "sir") s3_register("ggplot2::fortify", "mic") s3_register("ggplot2::fortify", "disk") # Support for knitr (R Markdown/Quarto) s3_register("knitr::knit_print", "antibiogram") s3_register("knitr::knit_print", "formatted_bug_drug_combinations") # Support vctrs package for use in e.g. dplyr verbs # S3: ab_selector s3_register("vctrs::vec_ptype2", "character.ab_selector") s3_register("vctrs::vec_ptype2", "ab_selector.character") s3_register("vctrs::vec_cast", "character.ab_selector") # S3: ab_selector_any_all s3_register("vctrs::vec_ptype2", "logical.ab_selector_any_all") s3_register("vctrs::vec_ptype2", "ab_selector_any_all.logical") s3_register("vctrs::vec_cast", "logical.ab_selector_any_all") # S3: ab s3_register("vctrs::vec_ptype2", "character.ab") s3_register("vctrs::vec_ptype2", "ab.character") s3_register("vctrs::vec_cast", "character.ab") s3_register("vctrs::vec_cast", "ab.character") # S3: av s3_register("vctrs::vec_ptype2", "character.av") s3_register("vctrs::vec_ptype2", "av.character") s3_register("vctrs::vec_cast", "character.av") s3_register("vctrs::vec_cast", "av.character") # S3: mo s3_register("vctrs::vec_ptype2", "character.mo") s3_register("vctrs::vec_ptype2", "mo.character") s3_register("vctrs::vec_cast", "character.mo") s3_register("vctrs::vec_cast", "mo.character") # S3: disk s3_register("vctrs::vec_ptype2", "integer.disk") s3_register("vctrs::vec_ptype2", "disk.integer") s3_register("vctrs::vec_cast", "integer.disk") s3_register("vctrs::vec_cast", "disk.integer") s3_register("vctrs::vec_cast", "double.disk") s3_register("vctrs::vec_cast", "disk.double") s3_register("vctrs::vec_cast", "character.disk") s3_register("vctrs::vec_cast", "disk.character") # S3: mic s3_register("vctrs::vec_cast", "character.mic") s3_register("vctrs::vec_cast", "double.mic") s3_register("vctrs::vec_cast", "mic.character") s3_register("vctrs::vec_cast", "mic.double") s3_register("vctrs::vec_math", "mic") # S3: sir s3_register("vctrs::vec_ptype2", "character.sir") s3_register("vctrs::vec_ptype2", "sir.character") s3_register("vctrs::vec_cast", "character.sir") s3_register("vctrs::vec_cast", "sir.character") # 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) } # be sure to print tibbles as tibbles if (pkg_is_available("tibble")) { try(loadNamespace("tibble"), silent = TRUE) } # reference data - they have additional data to improve algorithm speed # they cannot be part of R/sysdata.rda since CRAN thinks it would make the package too large (+3 MB) AMR_env$AB_lookup <- cbind(AMR::antibiotics, AB_LOOKUP) AMR_env$AV_lookup <- cbind(AMR::antivirals, AV_LOOKUP) } .onAttach <- function(lib, pkg) { # if custom ab option is available, load it if (!is.null(getOption("AMR_custom_ab")) && file.exists(getOption("AMR_custom_ab", default = ""))) { packageStartupMessage("Adding custom antimicrobials from '", getOption("AMR_custom_ab"), "'...", appendLF = FALSE) x <- readRDS_AMR(getOption("AMR_custom_ab")) tryCatch( { suppressWarnings(suppressMessages(add_custom_antimicrobials(x))) packageStartupMessage("OK.") }, error = function(e) packageStartupMessage("Failed: ", e$message) ) } # if custom mo option is available, load it if (!is.null(getOption("AMR_custom_mo")) && file.exists(getOption("AMR_custom_mo", default = ""))) { packageStartupMessage("Adding custom microorganisms from '", getOption("AMR_custom_mo"), "'...", appendLF = FALSE) x <- readRDS_AMR(getOption("AMR_custom_mo")) tryCatch( { suppressWarnings(suppressMessages(add_custom_microorganisms(x))) packageStartupMessage("OK.") }, error = function(e) packageStartupMessage("Failed: ", e$message) ) } }
/scratch/gouwar.j/cran-all/cranData/AMR/R/zzz.R
## ----setup, include = FALSE, results = 'markup'------------------------------- knitr::opts_chunk$set( warning = FALSE, collapse = TRUE, comment = "#>", fig.width = 7.5, fig.height = 5 )
/scratch/gouwar.j/cran-all/cranData/AMR/inst/doc/welcome_to_AMR.R
--- title: "Welcome to the `AMR` package" output: rmarkdown::html_vignette: toc: true toc_depth: 3 vignette: > %\VignetteIndexEntry{Welcome to the `AMR` package} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r setup, include = FALSE, results = 'markup'} knitr::opts_chunk$set( warning = FALSE, collapse = TRUE, comment = "#>", fig.width = 7.5, fig.height = 5 ) ``` Note: to keep the package size as small as possible, we only include this vignette on CRAN. You can read more vignettes on our website about how to conduct AMR data analysis, determine MDROs, find explanation of EUCAST and CLSI breakpoints, and much more: <https://msberends.github.io/AMR/articles/>. ---- The `AMR` package is a [free and open-source](https://msberends.github.io/AMR/#copyright) R package with [zero dependencies](https://en.wikipedia.org/wiki/Dependency_hell) to simplify the analysis and prediction of Antimicrobial Resistance (AMR) and to work with microbial and antimicrobial data and properties, by using evidence-based methods. **Our aim is to provide a standard** for clean and reproducible AMR data analysis, that can therefore empower epidemiological analyses to continuously enable surveillance and treatment evaluation in any setting. [Many different researchers](https://msberends.github.io/AMR/authors.html) from around the globe are continually helping us to make this a successful and durable project! This work was published in the Journal of Statistical Software (Volume 104(3); [DOI 10.18637/jss.v104.i03](https://doi.org/10.18637/jss.v104.i03)) and formed the basis of two PhD theses ([DOI 10.33612/diss.177417131](https://doi.org/10.33612/diss.177417131) and [DOI 10.33612/diss.192486375](https://doi.org/10.33612/diss.192486375)). After installing this package, R knows `r AMR:::format_included_data_number(AMR::microorganisms)` distinct microbial species and all `r AMR:::format_included_data_number(rbind(AMR::antibiotics[, "atc", drop = FALSE], AMR::antivirals[, "atc", drop = FALSE]))` antibiotic, antimycotic and antiviral drugs by name and code (including ATC, EARS-Net, ASIARS-Net, PubChem, LOINC and SNOMED CT), and knows all about valid SIR and MIC values. The integral breakpoint guidelines from CLSI and EUCAST are included from the last 10 years. It supports and can read any data format, including WHONET data. With the help of contributors from all corners of the world, the `AMR` package is available in English, Czech, Chinese, Danish, Dutch, Finnish, French, German, Greek, Italian, Japanese, Norwegian, Polish, Portuguese, Romanian, Russian, Spanish, Swedish, Turkish, and Ukrainian. Antimicrobial drug (group) names and colloquial microorganism names are provided in these languages. This package is fully independent of any other R package and works on Windows, macOS and Linux with all versions of R since R-3.0 (April 2013). **It was designed to work in any setting, including those with very limited resources**. Since its first public release in early 2018, this package has been downloaded from more than 175 countries. This package can be used for: * Reference for the taxonomy of microorganisms, since the package contains all microbial (sub)species from the List of Prokaryotic names with Standing in Nomenclature (LPSN) and the Global Biodiversity Information Facility (GBIF) * Interpreting raw MIC and disk diffusion values, based on the latest CLSI or EUCAST guidelines * Retrieving antimicrobial drug names, doses and forms of administration from clinical health care records * Determining first isolates to be used for AMR data analysis * Calculating antimicrobial resistance * Determining multi-drug resistance (MDR) / multi-drug resistant organisms (MDRO) * Calculating (empirical) susceptibility of both mono therapy and combination therapies * Predicting future antimicrobial resistance using regression models * Getting properties for any microorganism (like Gram stain, species, genus or family) * Getting properties for any antibiotic (like name, code of EARS-Net/ATC/LOINC/PubChem, defined daily dose or trade name) * Plotting antimicrobial resistance * Applying EUCAST expert rules * Getting SNOMED codes of a microorganism, or getting properties of a microorganism based on a SNOMED code * Getting LOINC codes of an antibiotic, or getting properties of an antibiotic based on a LOINC code * Machine reading the EUCAST and CLSI guidelines from 2011-2020 to translate MIC values and disk diffusion diameters to SIR * Principal component analysis for AMR All reference data sets (about microorganisms, antibiotics, SIR interpretation, EUCAST rules, etc.) in this `AMR` package are publicly and freely available. We continually export our data sets to formats for use in R, SPSS, SAS, Stata and Excel. We also supply flat files that are machine-readable and suitable for input in any software program, such as laboratory information systems. Please find [all download links on our website](https://msberends.github.io/AMR/articles/datasets.html), which is automatically updated with every code change. This R package was created for both routine data analysis and academic research at the Faculty of Medical Sciences of the [University of Groningen](https://www.rug.nl), in collaboration with non-profit organisations [Certe Medical Diagnostics and Advice Foundation](https://www.certe.nl) and [University Medical Center Groningen](https://www.umcg.nl), and is being [actively and durably maintained](https://msberends.github.io/AMR/news/) by two public healthcare organisations in the Netherlands. ---- <small> This AMR package for R is free, open-source software and licensed under the [GNU General Public License v2.0 (GPL-2)](https://msberends.github.io/AMR/LICENSE-text.html). These requirements are consequently legally binding: modifications must be released under the same license when distributing the package, changes made to the code must be documented, source code must be made available when the package is distributed, and a copy of the license and copyright notice must be included with the package. </small>
/scratch/gouwar.j/cran-all/cranData/AMR/inst/doc/welcome_to_AMR.Rmd
--- title: "Welcome to the `AMR` package" output: rmarkdown::html_vignette: toc: true toc_depth: 3 vignette: > %\VignetteIndexEntry{Welcome to the `AMR` package} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r setup, include = FALSE, results = 'markup'} knitr::opts_chunk$set( warning = FALSE, collapse = TRUE, comment = "#>", fig.width = 7.5, fig.height = 5 ) ``` Note: to keep the package size as small as possible, we only include this vignette on CRAN. You can read more vignettes on our website about how to conduct AMR data analysis, determine MDROs, find explanation of EUCAST and CLSI breakpoints, and much more: <https://msberends.github.io/AMR/articles/>. ---- The `AMR` package is a [free and open-source](https://msberends.github.io/AMR/#copyright) R package with [zero dependencies](https://en.wikipedia.org/wiki/Dependency_hell) to simplify the analysis and prediction of Antimicrobial Resistance (AMR) and to work with microbial and antimicrobial data and properties, by using evidence-based methods. **Our aim is to provide a standard** for clean and reproducible AMR data analysis, that can therefore empower epidemiological analyses to continuously enable surveillance and treatment evaluation in any setting. [Many different researchers](https://msberends.github.io/AMR/authors.html) from around the globe are continually helping us to make this a successful and durable project! This work was published in the Journal of Statistical Software (Volume 104(3); [DOI 10.18637/jss.v104.i03](https://doi.org/10.18637/jss.v104.i03)) and formed the basis of two PhD theses ([DOI 10.33612/diss.177417131](https://doi.org/10.33612/diss.177417131) and [DOI 10.33612/diss.192486375](https://doi.org/10.33612/diss.192486375)). After installing this package, R knows `r AMR:::format_included_data_number(AMR::microorganisms)` distinct microbial species and all `r AMR:::format_included_data_number(rbind(AMR::antibiotics[, "atc", drop = FALSE], AMR::antivirals[, "atc", drop = FALSE]))` antibiotic, antimycotic and antiviral drugs by name and code (including ATC, EARS-Net, ASIARS-Net, PubChem, LOINC and SNOMED CT), and knows all about valid SIR and MIC values. The integral breakpoint guidelines from CLSI and EUCAST are included from the last 10 years. It supports and can read any data format, including WHONET data. With the help of contributors from all corners of the world, the `AMR` package is available in English, Czech, Chinese, Danish, Dutch, Finnish, French, German, Greek, Italian, Japanese, Norwegian, Polish, Portuguese, Romanian, Russian, Spanish, Swedish, Turkish, and Ukrainian. Antimicrobial drug (group) names and colloquial microorganism names are provided in these languages. This package is fully independent of any other R package and works on Windows, macOS and Linux with all versions of R since R-3.0 (April 2013). **It was designed to work in any setting, including those with very limited resources**. Since its first public release in early 2018, this package has been downloaded from more than 175 countries. This package can be used for: * Reference for the taxonomy of microorganisms, since the package contains all microbial (sub)species from the List of Prokaryotic names with Standing in Nomenclature (LPSN) and the Global Biodiversity Information Facility (GBIF) * Interpreting raw MIC and disk diffusion values, based on the latest CLSI or EUCAST guidelines * Retrieving antimicrobial drug names, doses and forms of administration from clinical health care records * Determining first isolates to be used for AMR data analysis * Calculating antimicrobial resistance * Determining multi-drug resistance (MDR) / multi-drug resistant organisms (MDRO) * Calculating (empirical) susceptibility of both mono therapy and combination therapies * Predicting future antimicrobial resistance using regression models * Getting properties for any microorganism (like Gram stain, species, genus or family) * Getting properties for any antibiotic (like name, code of EARS-Net/ATC/LOINC/PubChem, defined daily dose or trade name) * Plotting antimicrobial resistance * Applying EUCAST expert rules * Getting SNOMED codes of a microorganism, or getting properties of a microorganism based on a SNOMED code * Getting LOINC codes of an antibiotic, or getting properties of an antibiotic based on a LOINC code * Machine reading the EUCAST and CLSI guidelines from 2011-2020 to translate MIC values and disk diffusion diameters to SIR * Principal component analysis for AMR All reference data sets (about microorganisms, antibiotics, SIR interpretation, EUCAST rules, etc.) in this `AMR` package are publicly and freely available. We continually export our data sets to formats for use in R, SPSS, SAS, Stata and Excel. We also supply flat files that are machine-readable and suitable for input in any software program, such as laboratory information systems. Please find [all download links on our website](https://msberends.github.io/AMR/articles/datasets.html), which is automatically updated with every code change. This R package was created for both routine data analysis and academic research at the Faculty of Medical Sciences of the [University of Groningen](https://www.rug.nl), in collaboration with non-profit organisations [Certe Medical Diagnostics and Advice Foundation](https://www.certe.nl) and [University Medical Center Groningen](https://www.umcg.nl), and is being [actively and durably maintained](https://msberends.github.io/AMR/news/) by two public healthcare organisations in the Netherlands. ---- <small> This AMR package for R is free, open-source software and licensed under the [GNU General Public License v2.0 (GPL-2)](https://msberends.github.io/AMR/LICENSE-text.html). These requirements are consequently legally binding: modifications must be released under the same license when distributing the package, changes made to the code must be documented, source code must be made available when the package is distributed, and a copy of the license and copyright notice must be included with the package. </small>
/scratch/gouwar.j/cran-all/cranData/AMR/vignettes/welcome_to_AMR.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' @export NULL
/scratch/gouwar.j/cran-all/cranData/ANN2/R/RcppExports.R
# This dummy function definition is included with the package to ensure that # 'tools::package_native_routine_registration_skeleton()' generates the required # registration info for the 'run_testthat_tests' symbol. (function() { .Call("run_testthat_tests", FALSE, PACKAGE = "ANN2") })
/scratch/gouwar.j/cran-all/cranData/ANN2/R/catch-routine-registration.R
#' @title Sets list with meta info, to be used in other checks #' @description #' Set network meta info #' @keywords internal setMeta <- function(data, hidden.layers, regression, autoencoder) { # Check if network has no hidden layers, set n_hidden layers accordingly if ( is.null(hidden.layers) || all(is.na(hidden.layers)) ) { no_hidden <- TRUE n_hidden <- 0 } else { no_hidden <- FALSE n_hidden <- length(hidden.layers) } # Set number of nodes in input and output layer n_in <- ncol(data$X) n_out <- ncol(data$y) # Set number of observations n_obs <- nrow(data$X) return( list(no_hidden = no_hidden, n_hidden = n_hidden, n_in = n_in, n_out = n_out, n_obs = n_obs, regression = regression, classes = data$classes, names = data$names, hidden_layers = hidden.layers, autoencoder = autoencoder) ) } #' @title Check the input data #' @description #' Set and check data #' @keywords internal setData <- function(X, y, regression, y_names = NULL) { # Convert X to matrix X <- as.matrix(X) # (ERROR) missing values in X and y miss_X <- any(is.na(X)) miss_y <- any(is.na(y)) if ( miss_X && miss_y ) { stop('X and y contain missing values', call. = FALSE) } else if ( miss_X ) { stop('X contain missing values', call. = FALSE) } else if ( miss_y ) { stop('y contain missing values', call. = FALSE) } # (ERROR) matrix X all numeric columns if ( !all(apply(X, 2, is.numeric)) ) { stop('X should be numeric', call. = FALSE) } # Checks on y for regression and classification if ( regression ) { # Convert y to matrix y <- as.matrix(y) # (ERROR) matrix y all numeric columns if ( !all(apply(y, 2, is.numeric)) ) { stop('y should be numeric for regression', call. = FALSE) } # Set names to class names (used in predict.ANN() ) y_names <- colnames(y) # If names are NULL, set if ( is.null(y_names) ) { y_names <- paste0('y_', seq(1,ncol(y))) } } else { # (ERROR) matrix y not single column if ( NCOL(y) != 1 ) { stop('y should be a vector or single-column matrix containing classes for classification', call. = FALSE) } # (ERROR) not enough classes for classification in y if ( length(unique(y)) < 1 ) { stop('y contains one or less classes, minimum of two required for classification', call. = FALSE) } # Convert y to matrix y <- as.matrix(y) # If y_names NULL (first training run) then y_names should be derived # from the data. If not NULL, y_names of first training run are used if ( is.null(y_names) ) { y_names <- as.character(sort(unique(y))) } # One-hot encode y and store classes y <- 1 * outer(c(y), y_names, '==') } # Set number of observations n_obs <- nrow(X) # (ERROR) not same number of observations in X and y if ( n_obs != nrow(y) ) { stop('Unequal numbers of observations in X and y', call. = FALSE) } # Collect parameters in list return ( list(X = X, y = y, y_names = y_names, n_obs = n_obs) ) } #' @title Check user input related to network structure #' @description #' Set and check network parameter list #' @keywords internal setNetworkParams <- function(hidden.layers, standardize, verbose, meta) { # Booleans for standardizing X and y stand_X <- standardize stand_y <- ifelse(meta$regression, standardize, FALSE) # Check if hidden layers NULL if ( meta$no_hidden ) { # Only input and output layers num_nodes <- as.integer( c(meta$n_in, meta$n_out) ) } else { # (ERROR) missing in hidden.layers if ( any(is.na(hidden.layers)) ) { stop('hidden.layers contains NA', call. = FALSE) } # (ERROR) non-integers in hidden.layers if ( !all(hidden.layers %% 1 == 0) ) { stop('hidden.layers contains non-integers', call. = FALSE) } # Set vector with structure (number of nodes) in the network num_nodes <- as.integer( c(meta$n_in, hidden.layers, meta$n_out) ) } # Collect parameters in list return ( list(num_nodes = num_nodes, stand_X = stand_X, stand_y = stand_y, verbose = verbose, regression = meta$regression, autoencoder = meta$autoencoder) ) } #' @title Check user input related to activation functions #' @description #' Set and check activation parameter list #' @keywords internal setActivParams <- function(activ.functions, step.H, step.k, meta) { allowed_types <- c('tanh', 'sigmoid', 'relu', 'linear', 'ramp', 'step') # Determine output type output_type <- ifelse(meta$regression, 'linear', 'softmax') # Check if no hidden layers if ( meta$no_hidden ) { # (WARN) no hidden layers so activ.functions will not be used if ( !is.null(activ.functions) && !all(is.na(activ.functions)) ) { warning('network with no hidden layers, specified activ.functions not used', call. = FALSE) } # Append activation type of output layer (and 'input', not used) types <- c('input', output_type) } else { # (ERROR) activ.functions not of allowed types if ( !(all(activ.functions %in% allowed_types)) ) { stop('activ.functions not all one of types ', paste(allowed_types, collapse = ', '), call. = FALSE) } # Single activ.function specified by user (or incorrect number of values) if ( length(activ.functions) != meta$n_hidden ) { # Broadcasting or throw error if ( length(activ.functions) == 1 ) { # Broadcast single activ.function over all hidden layers types <- c('input', rep(activ.functions, meta$n_hidden), output_type) } else { # (ERROR) length of activ.functions either 1 (broadcasting) or equal to the # number of hidden layers stop('length of activ.functions should be either one (for broadcasting) or equal to number of hidden layers', call. = FALSE) } } else { # No broadcasting types <- c('input', activ.functions, output_type) } } # Check parameters H and k, only for step activation function if ( 'step' %in% activ.functions ) { # (ERROR) number of steps H should be a whole number larger than zero if ( step.H %% 1 != 0 || step.H < 1 ) { stop('step.H should be an integer larger than zero', call. = FALSE) } # (ERROR) smoothing parameter k should be and integer larger than zero if ( step.k %% 1 != 0 || step.k < 1 ) { stop('step.k should be an integer larger than zero', call. = FALSE) } } # Collect parameters in list return ( list(types = types, step_H = step.H, step_k = step.k) ) } #' @title Check user input related to optimizer #' @description #' Set and check optimizer parameter list #' @keywords internal setOptimParams <- function(optim.type, learn.rates, L1, L2, sgd.momentum, rmsprop.decay, adam.beta1, adam.beta2, meta) { # Allowed optimizer types allowed_types <- c('sgd', 'rmsprop', 'adam') # (ERROR) optim.type not of allowed type if ( !(optim.type %in% allowed_types) ) { stop('optim.type not one of types ', paste(allowed_types, collapse = ', ')) } # (ERROR) missing learn.rates if ( is.null(learn.rates) || any(is.na(learn.rates)) ) { stop('missing value in learn.rates or learn.rates is NULL', call. = FALSE) } # (ERROR) learn.rate incorrect value if ( any(learn.rates <= 0) ) { stop('learn rates should be larger than 0', call. = FALSE) } # (ERROR) L1 and/or L2 incorrect value(s) if ( L1 < 0 || L2 < 0 ) { stop('L1 and/or L2 negative', call. = FALSE) } # Checks specific to SGD optimizer if ( optim.type == 'sgd' ) { # (ERROR) momentum incorrect value if ( sgd.momentum >= 1 || sgd.momentum < 0 ) { stop('sgd.momentum larger than or equal to one or smaller than zero', call. = FALSE) } # Checks specific to RMSprop optimizer } else if ( optim.type == 'rmsprop' ) { # (ERROR) rmsprop.decay incorrect value if ( rmsprop.decay >= 1 || rmsprop.decay <= 0 ) { stop('rmsprop.decay should be between zero and one', call. = FALSE) } # Checks specific to ADAM optimizer } else if ( optim.type == 'adam' ) { # (ERROR) adam.beta1 incorrect value if ( adam.beta1 >= 1 || adam.beta1 <= 0 ) { stop('adam.beta1 should be between zero and one', call. = FALSE) } # (ERROR) adam.beta2 incorrect value if ( adam.beta2 >= 1 || adam.beta2 <= 0 ) { stop('adam.beta2 should be between zero and one', call. = FALSE) } } else { # Not implemented optimizer stop('optim.type not supported') } # Length of learn.rates does not mach number of optimizers if ( length(learn.rates) != meta$n_hidden + 1 ) { # Broadcasting or throw error if ( length(learn.rates) == 1 ) { # Broadcast single activ.function over all layers rates <- c(0, rep(learn.rates, meta$n_hidden + 1)) } else { # (ERROR) length of learn.rates should be either 1 (broadcasting) or # equal to the number of hidden layers + 1 stop('length of learn.rates should be one or equal to number of hidden layers + 1', call. = FALSE) } } else { # No broadcasting rates <- c(0, learn.rates) } # Collect parameters in list return ( list(type = optim.type, learn_rates = rates, L1 = L1, L2 = L2, sgd_momentum = sgd.momentum, rmsprop_decay = rmsprop.decay, adam_beta1 = adam.beta1, adam_beta2 = adam.beta2) ) } #' @title Check user input related to loss function #' @description #' Set and check loss parameter list #' @keywords internal setLossParams <- function(loss.type, huber.delta, meta) { allowed_types <- c('log', 'squared', 'absolute', 'huber', 'pseudo-huber') # (ERROR) loss.type one of allowed types if ( !(loss.type %in% allowed_types) ) { stop('loss.type not one of ', paste(allowed_types, collapse = ', '), call. = FALSE) } # (ERROR) do not use log loss for regression if ( meta$regression && loss.type == 'log' ) { stop('Do not use loss.type "log" for regression', call. = FALSE) } # (ERROR) use log loss for classification if ( !meta$regression && loss.type != 'log' ) { stop('Use loss.type "log" for classification', call. = FALSE) } # Checks on parameters specific to huber and pseudo-huber if ( loss.type %in% c('huber', 'pseudo-huber') ) { # (ERROR) delta should be non-negative if ( huber.delta < 0 ) { stop('huber.delta smaller than zero', call. = FALSE) } # (WARN) use absolute loss if delta equals zero if ( huber.delta == 0 ) { warning ('huber.delta equal to zero, this is equivalent to using absolute loss but less efficient', call. = FALSE) } } # Collect parameters in list return ( list(type = loss.type, huber_delta = huber.delta) ) } #' @title Check user input related to training #' @description #' Set training parameters #' @keywords internal setTrainParams <- function (n.epochs, batch.size, val.prop, drop.last, random.seed, data) { # Set random seed with set.seed(), this also sets the seed for RcppArmadillo # If NULL, we use the current time to set a seed. This is to prevent the exact # same result of neuralnetwork(), autoencoder() and train() if the seed has # not been changed between consecutive runs if ( is.null(random.seed) ) { random.seed <- as.integer(format(Sys.time(), '%H%M%S')) } set.seed(random.seed) # (ERROR) n.epochs not positive if ( n.epochs <= 0 ) { stop('n.epochs should be larger than zero', call. = FALSE) } # (ERROR) n.epochs not whole number if ( n.epochs %% 1 != 0 ) { stop('n.epochs not an integer', call. = FALSE) } # (ERROR) batch.size not positive if ( batch.size <= 0 ) { stop('batch.size should be larger than zero', call. = FALSE) } # (ERROR) batch.size not whole number if ( batch.size %% 1 != 0 ) { stop('batch.size not an integer', call. = FALSE) } # (ERROR) val.prop incorrect value if ( val.prop < 0 || val.prop >= 1) { stop('val.prop should be smaller than one and larger than or equal to zero', call. = FALSE) } # Size of training and validation sets n_train <- ceiling( data$n_obs * (1 - val.prop) ) n_val <- data$n_obs - n_train # (ERROR) batch.size larger than n_obs if ( batch.size > data$n_obs ) { stop('batch.size larger than total number of observations in X and y', call. = FALSE) } # (ERROR) batch.size larger than n_train if ( n_val > 0 && batch.size > n_train ) { stop('batch.size larger than size of training data (after training/validation subsetting)', call. = FALSE) } # (WARN) small validation set if ( val.prop > 0 && n_val < 25 ) { warning('small validation set, only ', n_val, ' observations', call. = FALSE) } # Collect parameters in list return ( list(n_epochs = n.epochs, batch_size = batch.size, val_prop = val.prop, drop_last = drop.last) ) }
/scratch/gouwar.j/cran-all/cranData/ANN2/R/checks.R
#' @title Train a Neural Network #' #' @description #' Construct and train a Multilayer Neural Network for regression or #' classification #' #' @details #' A genereric function for training Neural Networks for classification and #' regression problems. Various types of activation and loss functions are #' supported, as well as L1 and L2 regularization. Possible optimizer include #' SGD (with or without momentum), RMSprop and Adam. #' #' @references LeCun, Yann A., et al. "Efficient backprop." Neural networks: #' Tricks of the trade. Springer Berlin Heidelberg, 2012. 9-48. #' #' @param X matrix with explanatory variables #' @param y matrix with dependent variables. For classification this should be #' a one-columns matrix containing the classes - classes will be one-hot encoded. #' @param hidden.layers vector specifying the number of nodes in each layer. The #' number of hidden layers in the network is implicitly defined by the length of #' this vector. Set \code{hidden.layers} to \code{NA} for a network with no hidden #' layers #' @param regression logical indicating regression or classification. In case of #' TRUE (regression), the activation function in the last hidden layer will be the #' linear activation function (identity function). In case of FALSE (classification), #' the activation function in the last hidden layer will be the softmax, and the #' log loss function should be used. #' @param standardize logical indicating if X and Y should be standardized before #' training the network. Recommended to leave at \code{TRUE} for faster #' convergence. #' @param loss.type which loss function should be used. Options are "log", #' "squared", "absolute", "huber" and "pseudo-huber". The log loss function should #' be used for classification (regression = FALSE), and ONLY for classification. #' @param huber.delta used only in case of loss functions "huber" and "pseudo-huber". #' This parameter controls the cut-off point between quadratic and absolute loss. #' @param activ.functions character vector of activation functions to be used in #' each hidden layer. Possible options are 'tanh', 'sigmoid', 'relu', 'linear', #' 'ramp' and 'step'. Should be either the size of the number of hidden layers #' or equal to one. If a single activation type is specified, this type will be #' broadcasted across the hidden layers. #' @param step.H number of steps of the step activation function. Only applicable #' if activ.functions includes 'step'. #' @param step.k parameter controlling the smoothness of the step activation #' function. Larger values lead to a less smooth step function. Only applicable #' if activ.functions includes 'step'. #' @param optim.type type of optimizer to use for updating the parameters. Options #' are 'sgd', 'rmsprop' and 'adam'. SGD is implemented with momentum. #' @param learn.rates the size of the steps to make in gradient descent. If set #' too large, the optimization might not converge to optimal values. If set too #' small, convergence will be slow. Should be either the size of the number of #' hidden layers plus one or equal to one. If a single learn rate is specified, #' this learn rate will be broadcasted across the layers. #' @param L1 L1 regularization. Non-negative number. Set to zero for no regularization. #' @param L2 L2 regularization. Non-negative number. Set to zero for no regularization. #' @param sgd.momentum numeric value specifying how much momentum should be #' used. Set to zero for no momentum, otherwise a value between zero and one. #' @param rmsprop.decay level of decay in the rms term. Controls the strength #' of the exponential decay of the squared gradients in the term that scales the #' gradient before the parameter update. Common values are 0.9, 0.99 and 0.999. #' @param adam.beta1 level of decay in the first moment estimate (the mean). #' The recommended value is 0.9. #' @param adam.beta2 level of decay in the second moment estimate (the uncentered #' variance). The recommended value is 0.999. #' @param n.epochs the number of epochs to train. One epoch is a single iteration #' through the training data. #' @param batch.size the number of observations to use in each batch. Batch learning #' is computationally faster than stochastic gradient descent. However, large #' batches might not result in optimal learning, see Efficient Backprop by LeCun #' for details. #' @param drop.last logical. Only applicable if the size of the training set is not #' perfectly devisible by the batch size. Determines if the last chosen observations #' should be discarded (in the current epoch) or should constitute a smaller batch. #' Note that a smaller batch leads to a noisier approximation of the gradient. #' @param val.prop proportion of training data to use for tracking the loss on a #' validation set during training. Useful for assessing the training process and #' identifying possible overfitting. Set to zero for only tracking the loss on the #' training data. #' @param verbose logical indicating if additional information should be printed #' @param random.seed optional seed for the random number generator #' @return An \code{ANN} object. Use function \code{plot(<object>)} to assess #' loss on training and optionally validation data during training process. Use #' function \code{predict(<object>, <newdata>)} for prediction. #' @examples #' # Example on iris dataset #' # Prepare test and train sets #' random_draw <- sample(1:nrow(iris), size = 100) #' X_train <- iris[random_draw, 1:4] #' y_train <- iris[random_draw, 5] #' X_test <- iris[setdiff(1:nrow(iris), random_draw), 1:4] #' y_test <- iris[setdiff(1:nrow(iris), random_draw), 5] #' #' # Train neural network on classification task #' NN <- neuralnetwork(X = X_train, y = y_train, hidden.layers = c(5, 5), #' optim.type = 'adam', learn.rates = 0.01, val.prop = 0) #' #' # Plot the loss during training #' plot(NN) #' #' # Make predictions #' y_pred <- predict(NN, newdata = X_test) #' #' # Plot predictions #' correct <- (y_test == y_pred$predictions) #' plot(X_test, pch = as.numeric(y_test), col = correct + 2) #' #' @export neuralnetwork <- function(X, y, hidden.layers, regression = FALSE, standardize = TRUE, loss.type = "log", huber.delta = 1, activ.functions = "tanh", step.H = 5, step.k = 100, optim.type = "sgd", learn.rates = 1e-04, L1 = 0, L2 = 0, sgd.momentum = 0.9, rmsprop.decay = 0.9, adam.beta1 = 0.9, adam.beta2 = 0.999, n.epochs = 100, batch.size = 32, drop.last = TRUE, val.prop = 0.1, verbose = TRUE, random.seed = NULL) { # Perform checks on data, set meta data data <- setData(X, y, regression) meta <- setMeta(data, hidden.layers, regression, autoencoder = FALSE) # Set and check parameters net_param <- setNetworkParams(hidden.layers, standardize, verbose, meta) activ_param <- setActivParams(activ.functions, step.H, step.k, meta) optim_param <- setOptimParams(optim.type, learn.rates, L1, L2, sgd.momentum, rmsprop.decay, adam.beta1, adam.beta2, meta) loss_param <- setLossParams(loss.type, huber.delta, meta) # Set and check training parameters - not used during object initialization # Sets the random seed so must be called before initializing ANN object train_param <- setTrainParams(n.epochs, batch.size, val.prop, drop.last, random.seed, data) # Initialize new ANN object Rcpp_ANN <- new(ANN, data, net_param, optim_param, loss_param, activ_param) # Train the network Rcpp_ANN$train(data, train_param) # Create ANN object ANN <- list(Rcpp_ANN = Rcpp_ANN) class(ANN) <- 'ANN' return(ANN) } #' @title Train an Autoencoding Neural Network #' #' @description #' Construct and train an Autoencoder by setting the target variables equal #' to the input variables. The number of nodes in the middle layer should be #' smaller than the number of input variables in X in order to create a #' bottleneck layer. #' #' @details #' A function for training Autoencoders. During training, the network will learn a #' generalised representation of the data (generalised since the middle layer #' acts as a bottleneck, resulting in reproduction of only the most #' important features of the data). As such, the network models the normal state #' of the data and therefore has a denoising property. This property can be #' exploited to detect anomalies by comparing input to reconstruction. If the #' difference (the reconstruction error) is large, the observation is a possible #' anomaly. #' #' @param X matrix with explanatory variables #' @param hidden.layers vector specifying the number of nodes in each layer. The #' number of hidden layers in the network is implicitly defined by the length of #' this vector. Set \code{hidden.layers} to \code{NA} for a network with no hidden #' layers #' @param standardize logical indicating if X and Y should be standardized before #' training the network. Recommended to leave at \code{TRUE} for faster #' convergence. #' @param loss.type which loss function should be used. Options are "squared", #' "absolute", "huber" and "pseudo-huber" #' @param huber.delta used only in case of loss functions "huber" and "pseudo-huber". #' This parameter controls the cut-off point between quadratic and absolute loss. #' @param activ.functions character vector of activation functions to be used in #' each hidden layer. Possible options are 'tanh', 'sigmoid', 'relu', 'linear', #' 'ramp' and 'step'. Should be either the size of the number of hidden layers #' or equal to one. If a single activation type is specified, this type will be #' broadcasted across the hidden layers. #' @param step.H number of steps of the step activation function. Only applicable #' if activ.functions includes 'step' #' @param step.k parameter controlling the smoothness of the step activation #' function. Larger values lead to a less smooth step function. Only applicable #' if activ.functions includes 'step'. #' @param optim.type type of optimizer to use for updating the parameters. Options #' are 'sgd', 'rmsprop' and 'adam'. SGD is implemented with momentum. #' @param learn.rates the size of the steps to make in gradient descent. If set #' too large, the optimization might not converge to optimal values. If set too #' small, convergence will be slow. Should be either the size of the number of #' hidden layers plus one or equal to one. If a single learn rate is specified, #' this learn rate will be broadcasted across the layers. #' @param L1 L1 regularization. Non-negative number. Set to zero for no regularization. #' @param L2 L2 regularization. Non-negative number. Set to zero for no regularization. #' @param sgd.momentum numeric value specifying how much momentum should be #' used. Set to zero for no momentum, otherwise a value between zero and one. #' @param rmsprop.decay level of decay in the rms term. Controls the strength #' of the exponential decay of the squared gradients in the term that scales the #' gradient before the parameter update. Common values are 0.9, 0.99 and 0.999 #' @param adam.beta1 level of decay in the first moment estimate (the mean). #' The recommended value is 0.9 #' @param adam.beta2 level of decay in the second moment estimate (the uncentered #' variance). The recommended value is 0.999 #' @param n.epochs the number of epochs to train. One epoch is a single iteration #' through the training data. #' @param batch.size the number of observations to use in each batch. Batch learning #' is computationally faster than stochastic gradient descent. However, large #' batches might not result in optimal learning, see Efficient Backprop by LeCun #' for details. #' @param drop.last logical. Only applicable if the size of the training set is not #' perfectly devisible by the batch size. Determines if the last chosen observations #' should be discarded (in the current epoch) or should constitute a smaller batch. #' Note that a smaller batch leads to a noisier approximation of the gradient. #' @param val.prop proportion of training data to use for tracking the loss on a #' validation set during training. Useful for assessing the training process and #' identifying possible overfitting. Set to zero for only tracking the loss on the #' training data. #' @param verbose logical indicating if additional information should be printed #' @param random.seed optional seed for the random number generator #' @return An \code{ANN} object. Use function \code{plot(<object>)} to assess #' loss on training and optionally validation data during training process. Use #' function \code{predict(<object>, <newdata>)} for prediction. #' @examples #' # Autoencoder example #' X <- USArrests #' AE <- autoencoder(X, c(10,2,10), loss.type = 'pseudo-huber', #' activ.functions = c('tanh','linear','tanh'), #' batch.size = 8, optim.type = 'adam', #' n.epochs = 1000, val.prop = 0) #' #' # Plot loss during training #' plot(AE) #' #' # Make reconstruction and compression plots #' reconstruction_plot(AE, X) #' compression_plot(AE, X) #' #' # Reconstruct data and show states with highest anomaly scores #' recX <- reconstruct(AE, X) #' sort(recX$anomaly_scores, decreasing = TRUE)[1:5] #' #' @export autoencoder <- function(X, hidden.layers, standardize = TRUE, loss.type = "squared", huber.delta = 1, activ.functions = "tanh", step.H = 5, step.k = 100, optim.type = "sgd", learn.rates = 1e-04, L1 = 0, L2 = 0, sgd.momentum = 0.9, rmsprop.decay = 0.9, adam.beta1 = 0.9, adam.beta2 = 0.999, n.epochs = 100, batch.size = 32, drop.last = TRUE, val.prop = 0.1, verbose = TRUE, random.seed = NULL) { # Perform checks on data, set meta data data <- setData(X, X, regression = TRUE) meta <- setMeta(data, hidden.layers, regression = TRUE, autoencoder = TRUE) # Set and check parameters net_param <- setNetworkParams(hidden.layers, standardize, verbose, meta) activ_param <- setActivParams(activ.functions, step.H, step.k, meta) optim_param <- setOptimParams(optim.type, learn.rates, L1, L2, sgd.momentum, rmsprop.decay, adam.beta1, adam.beta2, meta) loss_param <- setLossParams(loss.type, huber.delta, meta) # Set and check training parameters - not used during object initialization # Sets the random seed so must be called before initializing ANN object train_param <- setTrainParams(n.epochs, batch.size, val.prop, drop.last, random.seed, data) # Initialize new ANN object Rcpp_ANN <- new(ANN, data, net_param, optim_param, loss_param, activ_param) # Train network Rcpp_ANN$train(data, train_param) # Create ANN object ANN <- list(Rcpp_ANN = Rcpp_ANN) class(ANN) <- 'ANN' return(ANN) } #' @title Continue training of a Neural Network #' #' @description #' Continue training of a neural network object returned by \code{neuralnetwork()} #' or \code{autoencoder()} #' #' @details #' A new validation set is randomly chosen. This can result in irregular jumps #' in the plot given by \code{plot.ANN()}. #' #' @references LeCun, Yann A., et al. "Efficient backprop." Neural networks: #' Tricks of the trade. Springer Berlin Heidelberg, 2012. 9-48. #' #' @param object object of class \code{ANN} produced by \code{neuralnetwork()} #' or \code{autoencoder()} #' @param X matrix with explanatory variables #' @param y matrix with dependent variables. Not required if object is an autoencoder #' @param n.epochs the number of epochs to train. This parameter largely determines #' the training time (one epoch is a single iteration through the training data). #' @param batch.size the number of observations to use in each batch. Batch learning #' is computationally faster than stochastic gradient descent. However, large #' batches might not result in optimal learning, see Efficient Backprop by Le Cun #' for details. #' @param drop.last logical. Only applicable if the size of the training set is not #' perfectly devisible by the batch size. Determines if the last chosen observations #' should be discarded (in the current epoch) or should constitute a smaller batch. #' Note that a smaller batch leads to a noisier approximation of the gradient. #' @param val.prop proportion of training data to use for tracking the loss on a #' validation set during training. Useful for assessing the training process and #' identifying possible overfitting. Set to zero for only tracking the loss on the #' training data. #' @param random.seed optional seed for the random number generator #' @return An \code{ANN} object. Use function \code{plot(<object>)} to assess #' loss on training and optionally validation data during training process. Use #' function \code{predict(<object>, <newdata>)} for prediction. #' @examples #' # Train a neural network on the iris dataset #' X <- iris[,1:4] #' y <- iris$Species #' NN <- neuralnetwork(X, y, hidden.layers = 10, sgd.momentum = 0.9, #' learn.rates = 0.01, val.prop = 0.3, n.epochs = 100) #' #' # Plot training and validation loss during training #' plot(NN) #' #' # Continue training for 1000 epochs #' train(NN, X, y, n.epochs = 200, val.prop = 0.3) #' #' # Again plot the loss - note the jump in the validation loss at the 100th epoch #' # This is due to the random selection of a new validation set #' plot(NN) #' @export train <- function(object, X, y = NULL, n.epochs = 100, batch.size = 32, drop.last = TRUE, val.prop = 0.1, random.seed = NULL) { # Extract meta from object meta <- object$Rcpp_ANN$getMeta() # Checks for different behavior autoencoder and normal neural net if ( meta$autoencoder ) { # Autoencoder but also Y specified if ( !is.null(y) ) { stop('Object of type autoencoder but y is given', call. = FALSE) } # Set Y equal to X y = X } else { # Not an autoencoder but no Y given if ( is.null(y) ) { stop('y matrix of dependent variables needed', call. = FALSE) } } # Perform checks on data, set meta data data <- setData(X, y, meta$regression, meta$y_names) # Set and check training parameters train_param <- setTrainParams(n.epochs, batch.size, val.prop, drop.last, random.seed, data) # Call train method object$Rcpp_ANN$train(data, train_param) } #' @title Reconstruct data using trained ANN object of type autoencoder #' #' @description #' \code{reconstruct} takes new data as input and reconstructs the observations using #' a trained replicator or autoencoder object. #' #' @details #' A genereric function for training neural nets #' #' @param object Object of class \code{ANN} created with \code{autoencoder()} #' @param X data matrix to reconstruct #' @return Reconstructed observations and anomaly scores (reconstruction errors) #' @export reconstruct <- function(object, X) { # Extract meta meta <- object$Rcpp_ANN$getMeta() # Convert X to matrix X <- as.matrix(X) # Reconstruct only relevant for NNs of type autoencoder if ( !meta$autoencoder ) { stop("Object is not of type autoencoder") } # (ERROR) missing values in X if ( any(is.na(X)) ) { stop('X contain missing values', call. = FALSE) } # (ERROR) matrix X all numeric columns if ( !all(apply(X, 2, is.numeric)) ) { stop('X should be numeric', call. = FALSE) } # (ERROR) incorrect number of columns of input data if ( ncol(X) != meta$n_in ) { stop('Input data incorrect number of columns', call. = FALSE) } # Make reconstruction, calculate the anomaly scores fit <- object$Rcpp_ANN$predict(X) colnames(fit) <- meta$y_names err <- rowSums( (fit - X)^2 ) / meta$n_out # Construct function output return( list(reconstructed = fit, anomaly_scores = err) ) } #' @title Make predictions for new data #' @description \code{predict} Predict class or value for new data #' @details A genereric function for training neural nets #' @method predict ANN #' @param object Object of class \code{ANN} #' @param newdata Data to make predictions on #' @param \dots further arguments (not in use) #' @return A list with predicted classes for classification and fitted probabilities #' @export predict.ANN <- function(object, newdata, ...) { # Extract meta meta <- object$Rcpp_ANN$getMeta() # Convert X to matrix X <- as.matrix(newdata) # (ERROR) missing values in X if ( any(is.na(X)) ) { stop('newdata contain missing values', call. = FALSE) } # (ERROR) matrix X all numeric columns if ( !all(apply(X, 2, is.numeric)) ) { stop('newdata should be numeric', call. = FALSE) } # Predict fit <- object$Rcpp_ANN$predict(X) # Set column names if (meta$regression) { colnames(fit) <- meta$y_names } else { colnames(fit) <- paste0("class_", meta$y_names) } # For regression return fitted values if ( meta$regression ) { return( list(predictions = fit) ) } # For classification return predicted classes and probabilities (fit) predictions <- meta$y_names[apply(fit, 1, which.max)] return( list(predictions = predictions, probabilities = fit) ) } #' @title Print ANN #' @description Print info on trained Neural Network #' @method print ANN #' @param x Object of class \code{ANN} #' @param \dots Further arguments #' @export print.ANN <- function(x, ...){ x$Rcpp_ANN$print( TRUE ) } #' @title Write ANN object to file #' @description Serialize ANN object to binary file #' @param object Object of class \code{ANN} #' @param file character specifying file path #' @export write_ANN <- function(object, file){ object$Rcpp_ANN$write(file) } #' @title Read ANN object from file #' @description Deserialize ANN object from binary file #' @param file character specifying file path #' @return Object of class ANN #' @export read_ANN <- function(file){ # Initialize new S4 object and call read method Rcpp_ANN <- new(ANN) Rcpp_ANN$read(file) # Create ANN object ANN <- list(Rcpp_ANN = Rcpp_ANN) class(ANN) <- 'ANN' return(ANN) } #' @title Encoding step #' @description Compress data according to trained replicator or autoencoder. #' Outputs are the activations of the nodes in the middle layer for each #' observation in \code{newdata} #' @param object Object of class \code{ANN} #' @param newdata Data to compress #' @param compression.layer Integer specifying which hidden layer is the #' compression layer. If NULL this parameter is inferred from the structure #' of the network (hidden layer with smallest number of nodes) #' @param \dots arguments to be passed down #' @export encode <- function(object, ...) UseMethod("encode") #' @rdname encode #' @method encode ANN #' @export encode.ANN <- function(object, newdata, compression.layer = NULL, ...) { # Extract meta, hidden_layers meta <- object$Rcpp_ANN$getMeta() hidden_layers <- meta$num_nodes[2:(1+meta$n_hidden)] # Check if autoencoder if ( !meta$autoencoder ) { warning("Object is not an autoencoder") } # Convert X to matrix X <- as.matrix(newdata) # (ERROR) missing values in X if ( any(is.na(X)) ) { stop('newdata contain missing values', call. = FALSE) } # (ERROR) matrix X all numeric columns if ( !all(apply(X, 2, is.numeric)) ) { stop('newdata should be numeric', call. = FALSE) } # (ERROR) incorrect number of columns of input data if ( ncol(X) != meta$n_in ) { stop('Input data incorrect number of columns', call. = FALSE) } # Determine compression layer if ( is.null(compression.layer) ) { # Compression layer is hidden layer with minimum number of nodes compression.layer <- which.min( hidden_layers ) # (ERROR) Ambiguous compression layer if ( sum( hidden_layers[compression.layer] == hidden_layers) > 1 ) { stop('Ambiguous compression layer, specify compression.layer', call. = FALSE) } } # Predict and set column names compressed <- object$Rcpp_ANN$partialForward(X, 0, compression.layer) colnames(compressed) <- paste0("node_", 1:NCOL(compressed)) return( compressed ) } #' @title Decoding step #' @description Decompress low-dimensional representation resulting from the nodes #' of the middle layer. Output are the reconstructed inputs to function \code{encode()} #' @param object Object of class \code{ANN} #' @param compressed Compressed data #' @param compression.layer Integer specifying which hidden layer is the #' compression layer. If NULL this parameter is inferred from the structure #' of the network (hidden layer with smallest number of nodes) #' @param \dots arguments to be passed down #' @export decode <- function(object, ...) UseMethod("decode") #' @rdname decode #' @method decode ANN #' @export decode.ANN <- function(object, compressed, compression.layer = NULL, ...) { # Extract meta, hidden_layers vector meta <- object$Rcpp_ANN$getMeta() hidden_layers <- meta$num_nodes[2:(1+meta$n_hidden)] if ( !meta$autoencoder ) { warning("Object is not an autoencoder") } # Convert X to matrix X <- as.matrix(compressed) # (ERROR) missing values in X if ( any(is.na(X)) ) { stop('compressed contain missing values', call. = FALSE) } # (ERROR) matrix X all numeric columns if ( !all(apply(X, 2, is.numeric)) ) { stop('compressed should be numeric', call. = FALSE) } # Determine compression layer if ( is.null(compression.layer) ) { # Compression layer is hidden layer with minimum number of nodes compression.layer <- which.min( hidden_layers ) # (ERROR) Ambiguous compression layer if ( sum( hidden_layers[compression.layer] == hidden_layers) > 1 ) { stop('Ambiguous compression layer, specify compression.layer', call. = FALSE) } } # (ERROR) incorrect number of columns of input data if ( ncol(X) != hidden_layers[compression.layer] ) { stop('Input data incorrect number of columns', call. = FALSE) } # Predict and set column names fit <- object$Rcpp_ANN$partialForward(X, compression.layer, meta$n_hidden + 1) colnames(fit) <- meta$y_names return( fit ) }
/scratch/gouwar.j/cran-all/cranData/ANN2/R/interface.R
Rcpp::loadModule("ANN", TRUE)
/scratch/gouwar.j/cran-all/cranData/ANN2/R/load_module.R
#' @useDynLib ANN2, .registration=TRUE #' @importFrom methods new #' @import ggplot2 #' @import reshape2 #' @import Rcpp NULL
/scratch/gouwar.j/cran-all/cranData/ANN2/R/namespace.R
#' @title Plot training and validation loss #' @description \code{plot} Generate plots of the loss against epochs #' @details A generic function for plot loss of neural net #' @method plot ANN #' @param x Object of class \code{ANN} #' @param max.points Maximum number of points to plot, set to NA, NULL or Inf to #' include all points in the plot #' @param ... further arguments to be passed to plot #' @return Plots #' @export plot.ANN <- function(x, max.points = 1000, ...) { if ( class(x)!='ANN' ) { stop('Object not of class ANN', call. = FALSE) } # Obtain training history from ANN object train_hist <- x$Rcpp_ANN$getTrainHistory() # Set maximum number of points to plot max.points <- min(train_hist$n_eval, max.points, na.rm = TRUE) # Select points to plot idx <- round(seq(1, train_hist$n_eval, length.out = max.points)) epochs <- train_hist$epoch[idx] # Interpolate duplicate epochs if (any(duplicated(epochs))) { epochs <- c(unlist(sapply(unique(epochs), function(xx) { n <- sum(epochs==xx)+1 seq(from = xx, to = xx+1, length.out = n)[-n] }))) } # Make df, add validation loss if applicable df <- data.frame(x = epochs, Training = train_hist$train_loss[idx]) if ( train_hist$validate ) { df$Validation <- train_hist$val_loss[idx] } # Meld df df_melt <- reshape2::melt(df, id.vars = 'x', value.name = 'y') # Viridis colors viridis_cols <- viridisLite::viridis(n = 2) # Return plot ggplot(data = df_melt) + geom_path(aes_string(x = 'x', y = 'y', color = 'variable')) + labs(x = 'Epoch', y = 'Loss') + scale_color_manual(name = NULL, values = c('Training' = viridis_cols[1], 'Validation' = viridis_cols[2])) } #' @title Reconstruction plot #' @description #' plots original and reconstructed data points in a single plot with connecting #' lines between original value and corresponding reconstruction #' @details Matrix plot of pairwise dimensions #' @param object autoencoder object of class \code{ANN} #' @param X data matrix with original values to be reconstructed and plotted #' @param colors optional vector of discrete colors. The reconstruction errors #' are are used as color if this argument is not specified #' @param \dots arguments to be passed down #' @return Plots #' @export reconstruction_plot <- function(object, ...) UseMethod("reconstruction_plot") #' @rdname reconstruction_plot #' @method reconstruction_plot ANN #' @export reconstruction_plot.ANN <- function(object, X, colors = NULL, ...) { # X as matrix and reconstuct X <- as.matrix(X) rec <- reconstruct(object, X) rX <- rec$reconstructed # Extract meta, set derived constants meta <- object$Rcpp_ANN$getMeta() n_row <- nrow(X) n_col <- meta$n_in dim_names <- meta$y_names # Create data.frame containing points for original values and reconstructions # This created the matrix like structure for pairwise plotting of dimensions dim_combinations <- as.matrix( expand.grid(seq_len(n_col), seq_len(n_col)) ) values <- apply( dim_combinations, 2, function(dc) X[,dc] ) recs <- apply( dim_combinations, 2, function(dc) rX[,dc] ) dims <- matrix( dim_names[rep(dim_combinations, each = n_row)], ncol = 2) df_plot <- data.frame(dims, values, recs, stringsAsFactors = TRUE) colnames(df_plot) <- c('x_dim', 'y_dim', 'x_val', 'y_val', 'x_rec', 'y_rec') # Create data.frame for x and y values seperately in order to create the # data.frame for connection lines between original points and reconstructions df_x <- df_plot[,c('x_dim', 'y_dim', 'x_val', 'x_rec')] df_y <- df_plot[,c('x_dim', 'y_dim', 'y_val', 'y_rec')] colnames(df_x) <- colnames(df_y) <- c('x_dim', 'y_dim', 'x', 'y') df_x$obs <- df_y$obs <- seq_len(nrow(df_plot)) # Melt data.frames and merge for connection lines df_lin_x <- melt(df_x, id.vars = c('obs', 'x_dim', 'y_dim')) df_lin_y <- melt(df_y, id.vars = c('obs', 'x_dim', 'y_dim')) df_lin <- merge(df_lin_x, df_lin_y, by = c('obs', 'x_dim', 'y_dim', 'variable')) if ( !is.null(colors) || !all(is.na(colors)) ) { df_plot$col <- colors gg_color <- scale_color_viridis_d(name = NULL) } else { df_plot$col <- rec$anomaly_scores gg_color <- scale_color_viridis_c(name = 'Rec. Err.') } # Create and return plot ggplot(data = df_plot) + geom_path(data = df_lin, aes_string(x = 'value.x', y = 'value.y', group = 'obs'), color = 'darkgrey') + geom_point(aes_string(x = 'x_rec', y = 'y_rec'), color = 'darkgrey') + geom_point(aes_string(x = 'x_val', y = 'y_val', color = 'col')) + facet_grid(y_dim ~ x_dim, scales = "free") + labs(x = NULL, y = NULL) + gg_color } #' @title Compression plot #' @description #' plot compressed observation in pairwise dimensions #' @details Matrix plot of pairwise dimensions #' @param object autoencoder object of class \code{ANN} #' @param X data matrix with original values to be compressed and plotted #' @param colors optional vector of discrete colors #' @param jitter logical specifying whether to apply jitter to the compressed #' values. Especially useful whith step activation function that clusters the #' compressions and reconstructions. #' @param \dots arguments to be passed to \code{jitter()} #' @return Plots #' @export compression_plot <- function(object, ...) UseMethod("compression_plot") #' @rdname compression_plot #' @method compression_plot ANN #' @export compression_plot.ANN <- function(object, X, colors = NULL, jitter = FALSE, ...) { # X as matrix and reconstuct X <- as.matrix(X) cX <- encode(object, X) # Apply jitter, arguments passed in ellipsis are passed to jitter if (jitter) { # Jitter function with new default arguments custom_jitter <- function(x, factor=1, amount=0) jitter(x, factor, amount) cX <- custom_jitter(cX, ...) } # Extract meta, set derived constants meta <- object$Rcpp_ANN$getMeta() n_row <- nrow(X) n_col <- ncol(cX) dim_names <- colnames(cX) # Create data.frame containing points for compressed values # This created the matrix like structure for pairwise plotting of dimensions dim_combinations <- as.matrix( expand.grid(seq_len(n_col), seq_len(n_col)) ) compr <- apply( dim_combinations, 2, function(dc) cX[,dc] ) dims <- matrix( dim_names[rep(dim_combinations, each = n_row)], ncol = 2) df_plot <- data.frame(dims, compr, stringsAsFactors = TRUE) colnames(df_plot) <- c('x_dim', 'y_dim', 'x_compr', 'y_compr') if ( !is.null(colors) || !all(is.na(colors)) ) { df_plot$col <- colors gg_color <- scale_color_viridis_d(name = NULL) } else { df_plot$col <- 'a' gg_color <- scale_color_viridis_d(guide = FALSE) } # Create and return plot ggplot(data = df_plot) + geom_point(aes_string(x = 'x_compr', y = 'y_compr', color = 'col')) + facet_grid(y_dim ~ x_dim, scales = "free") + labs(x = NULL, y = NULL) + gg_color }
/scratch/gouwar.j/cran-all/cranData/ANN2/R/plotting.R
#################################################################################### #' @title anofa: analysis of frequency data. #' #' @md #' #' @description The function `anofa()` performs an anofa of frequencies for designs with up to 4 factors #' according to the `anofa` framework. See \insertCite{lc23b;textual}{ANOFA} for more. #' #' #' @param data Dataframe in one of wide, long, raw or compiled format; #' #' @param formula A formula with the factors on the left-hand side. See below for writing the #' formula according to the data format. #' #' @param factors For raw data formats, provide the factor names. #' #' @return a model fit to the given frequencies. The model must always be an omnibus model (for #' decomposition of the main model, follow the analysis with `emFrequencies()` or `contrastFrequencies()`) #' #' #' @details The data can be given in four formats: #' * `wide`: In the wide format, there is one line for each participant, and #' one column for each factor in the design. In the column(s), the level must #' of the factor is given (as a number, a string, or a factor). #' * `long`: In the long format, there is an identifier column for each participant, #' a factor column and a level number for that factor. If there are n participants #' and m factors, there will be in total n x m lines. #' * `raw`: In the raw column, there are as many lines as participants, and as many columns as #' there are levels for each factors. Each cell is a 0|1 entry. #' * `compiled`: In the compiled format, there are as many lines as there are cells in the #' design. If there are two factors, with two levels each, there will be 4 lines. #' See the vignette `DataFormatsForFrequencies` for more on data format and how to write their formula. #' #' #' @references #' \insertAllCited #' #' @examples #' # Basic example using a single-factor design with the data in compiled format. #' # Ficticious data present frequency of observation classified according #' # to Intensity (three levels) and Pitch (two levels) for 6 possible cells. #' minimalExample #' #' formula <- Frequency ~ Intensity * Pitch #' w <- anofa(formula, minimalExample) #' summary(w) #' #' # To know more about other ways to format the datasets, #' # see, e.g., `toRaw()`, `toLong()`, `toWide()` #' w <- anofa(formula, minimalExample) #' toWide(w) #' # See the vignette `DataFormatsForFrequencies` for more. #' #' # Real-data example using a two-factor design with the data in compiled format: #' LandisBarrettGalvin2013 #' #' w <- anofa( obsfreq ~ program * provider, LandisBarrettGalvin2013 ) #' summary(w) #' #' # You can ask easier outputs #' w <- anofa(formula, minimalExample) #' summarize(w) # or summary(w) for the ANOFA table #' explain(w) # human-readable ouptut #' #################################################################################### #' @importFrom stats aggregate pchisq qchisq qf as.formula #' @importFrom utils combn #' @export anofa #' @importFrom utils capture.output # #################################################################################### anofa <- function( formula = NULL, #mandatory: the design of the data data = NULL, #mandatory: the data itself factors = NULL #optional: if the data are in raw format, name the factors ) { ############################################################################## # STEP 0: preliminary preparations... ############################################################################## data <- as.data.frame(data) # coerce to data.frame if tibble or compatible ############################################################################## # STEP 1: Input validation ############################################################################## # 1.1: is the formula actually a valid formula? if (!is.formula(formula)) stop("ANOFA::error(11): `formula` argument is not a legitimate formula. Exiting...") # 1.2: has the formula having 0 or 1 DV? if (length(formula)==3) { if (length(all.vars(formula[[2]]))!=1) stop("ANOFA::error(12): formula argument has more than 0 or 1 DV. Exiting...") } # 1.3: are the data actually data? if( (!is.data.frame(data)) || (dim(data)[2] <= 1)) stop("ANOFA::error(13): `data` argument is not a data.frame or similar data structure. Exiting...") # 1.4: are the columns named in the formula present in the data? vars <- all.vars(formula) # extract variables in cbind and with | alike if (!(all(vars %in% names(data)))) stop("ANOFA::error(14): variables in `formula` are not all in `data`. Exiting...") ############################################################################## # STEP 2: Harmonize the data format ############################################################################## # 2.1: Keep only the columns named data <- data[, names(data) %in% vars] # 2.2: Convert data to compiled format based on the formula if (is.one.sided( formula ) ) { # if no left-side terms: must be wide or raw formats if (has.cbind.terms( formula )) { # | : list all the variables # if there are cbind in rhs, must be raw format freq <- "Frequency" internalData <- rtoc(data, freq, formula, factors ) } else { # otherwise, must be wide format freq <- "Frequency" internalData <- wtoc(data, freq ) } } else { # if left-side term: must be compiled or long formats if (has.nested.terms( formula )) { # if | in lhs: must be long format freq <- "Frequency" internalData <- ltoc(data, freq, formula) } else { # if no | in lhs: must be compiled format: NOTHING TO DO! freq <- formula[[2]] internalData <- data } } # 2.3: Keep the factor names fact <- names(internalData)[ ! names(internalData) == freq] if( (length(fact)>4) || (length(fact) < 1)) stop("ANOFA::error(15): Too many factors. Exiting...") ############################################################################## # STEP 3: run the analysis, depending on the number of factors ############################################################################## # 3.1: to avoid integer overflow, convert frequencies to num internalData[[freq]] = as.numeric( internalData[[freq]]) # 3.2: perform the analysis based on the number of factors analysis <- switch( length(fact), anofa1way(internalData, freq, fact), anofa2way(internalData, freq, fact), anofa3way(internalData, freq, fact), anofa4way(internalData, freq, fact), ) ############################################################################## # STEP 4: return the object ############################################################################## # 4.1: preserve everything in an object of class ANOFAobject res <- list( type = "ANOFAomnibus", formula = as.formula(formula), compiledData = internalData, freqColumn = freq, factColumns = fact, nlevels = unlist(analysis[[1]]), clevels = analysis[[2]], results = analysis[[3]] ) class(res) <- c("ANOFAobject", class(res) ) return( res ) } ############################################################################## # Subfunctions ############################################################################## anofa1way <- function(dataC, freq, factor) { # First, we determine the number of levels for the factor A <- length(unique(dataC[[factor]])) clevels <- list(as.character(unique(dataC[[factor]]))) # Second, we compute the cell frequencies ni nd <- sum(dataC[[freq]]) ni <- unlist(dataC[[freq]]) # Third, we computed the expected frequencies e ei <- nd * rep(1/A, A) # Fourth, get the G statistics Gtotal <- 2 * sum(sum(ni * (log(ni)- log(ei)))) # Fifth, the correction factor (Williams, 1976) ctotal <- 1+ (A^2-1)/ ( 6 * (A-1) * nd) # Finally, getting the p-values for each corrected effect ptotal = 1- pchisq(Gtotal/ ctotal, df = A-1) results <- data.frame( G = Gtotal, df = A-1, Gcorrected = Gtotal/ ctotal, pvalue = ptotal, etasq = anofaES(ni / nd) ) rownames(results) <- factor return( list( list(A), clevels, results )) } anofa2way <- function(dataC, freq, factors ) { # First, we determine the number of levels for each factors A <- length(unique(dataC[[factors[1]]])) B <- length(unique(dataC[[factors[2]]])) # Second, we compute the marginal frequencies n ndd <- sum(dataC[[freq]]) nid <- aggregate(as.formula(paste(freq, factors[1], sep="~")), data = dataC, sum)[[freq]] ndj <- aggregate(as.formula(paste(freq, factors[2], sep="~")), data = dataC, sum)[[freq]] # ... and the observed frequencies in a matrix # nij <- matrix(rep(0, A*B), ncol = B) # for (i in 1:A) { # for (j in 1:B) { # nij[i,j] = dataC[dataC[[factors[1]]]==unique(dataC[[factors[1]]])[i] & dataC[[factors[2]]]==unique(dataC[[factors[2]]])[j],][[freq]] # } # } #print(nij) #print("Ss") #print(paste(freq, paste(factors, collapse="+"),sep="~")) temp <- aggregate(as.formula(paste(freq, paste(factors, collapse="+"),sep="~")), data = dataC, sum) #print(temp) nij <- matrix(temp[[freq]], A) #print(nij) clevels <- list(as.character(unique(temp[[factors[[1]]]])), as.character(unique(temp[[factors[[2]]]]))) #print(clevels) # Third, we computed the expected frequencies e edd <- ndd / (A * B) eid <- ndd / A edj <- ndd / B eij <- outer(nid, ndj)/ndd #print(dim(nij)) #print(dim(eij)) # Fourth, get the G statistics Gtotal <- 2 * sum(sum(nij * (log(nij)- log(edd)))) Grow <- 2 * sum(sum(nid * (log(nid)- log(eid)))) Gcol <- 2 * sum(sum(ndj * (log(ndj)- log(edj)))) Grxc <- 2 * sum(sum(nij * (log(nij)- log(eij)))) # Fifth, the correction factor (Williams, 1976) for each factor crow <- 1+ (A^2-1)/ ( 6 * (A-1) * ndd) ccol <- 1+ (B^2-1)/ ( 6 * (B-1) * ndd) crxc <- 1+ ((A*B)^2-1)/ ( 6 * (A-1) * (B-1) * ndd) # Finally, getting the p-values for each corrected effect prow = 1- pchisq(Grow/ crow, df = A-1) pcol = 1- pchisq(Gcol/ ccol, df = B-1) prxc = 1- pchisq(Grxc/ crxc, df = (A-1)*(B-1)) # assembling the results in a table results <- data.frame( G = c(Gtotal, Grow, Gcol, Grxc), df = c(A*B-1, A-1, B-1, (A-1)*(B-1)), Gcorrected = c(NA, Grow/ crow, Gcol/ ccol, Grxc/ crxc), pvalue = c(NA, prow, pcol, prxc), etasq = c(NA, anofaES(nid/ndd), anofaES(ndj/ndd), anofaES(nij/ndd) ) ) rownames(results) <-c("Total", factors, paste(factors, collapse=":")) return( list( list(A, B), clevels, results )) } anofa3way <- function(dataC, freq, factors ) { # First, we determine the number of levels for each factors A <- length(unique(dataC[[factors[1]]])) B <- length(unique(dataC[[factors[2]]])) C <- length(unique(dataC[[factors[3]]])) # Second, we compute the grand total and the marginal frequencies in n variables # The factors are noted with the letters i, j, k and l # In this notation, "d" denotes the dot. nddd <- sum(dataC[[freq]]) # first-order marginals nidd <- aggregate(as.formula(paste(freq, factors[1], sep="~")), data = dataC, sum)[[freq]] ndjd <- aggregate(as.formula(paste(freq, factors[2], sep="~")), data = dataC, sum)[[freq]] nddk <- aggregate(as.formula(paste(freq, factors[3], sep="~")), data = dataC, sum)[[freq]] # second-order marginals by2 <-lapply(combn(factors,2,simplify=FALSE), function(x) paste(x, collapse=" + ")) nijd <- matrix(aggregate(as.formula(paste(freq, by2[[1]],sep="~")), data = dataC, sum)[[freq]], A) nidk <- matrix(aggregate(as.formula(paste(freq, by2[[2]],sep="~")), data = dataC, sum)[[freq]], A) ndjk <- matrix(aggregate(as.formula(paste(freq, by2[[3]],sep="~")), data = dataC, sum)[[freq]], B) # and finally the observed frequencies in a matrix nijk <- array( (temp <- aggregate(as.formula(paste(freq, paste(factors, collapse="*"),sep="~")), data = dataC, sum))[[freq]],c(A,B,C)) # we preserve the label names in the order of the aggregate (which tend to change ordering...) clevels <- list(as.character(unique(temp[[factors[[1]]]])), as.character(unique(temp[[factors[[2]]]])), as.character(unique(temp[[factors[[3]]]]))) # Third, we computed the expected frequencies e eddd <- nddd / (A * B * C) # first-order expectation eidd <- rep(nddd / A, A) edjd <- rep(nddd / B, B) eddk <- rep(nddd / C, C) # second-order expectation eijd <- outer(nidd, ndjd)/nddd eidk <- outer(nidd, nddk)/nddd edjk <- outer(ndjd, nddk)/nddd # third-order expectation (there might be a matrix operation for that?) eijk <- array(NA, c(A,B,C)) for(i in 1:A) for(j in 1:B) for(k in 1:C) { eijk[i,j,k] <- nddd * ( nijd[i,j] * nidk[i,k] * ndjk[j,k] ) / ( nidd[i] * ndjd[j] * nddk[k] ) } # Fourth, get the G statistics Gtotal <- 2 * sum(sum(sum(sum(nijk * (log(nijk)- log(eddd)))))) # for the main effects Gidd <- 2 * sum(nidd * (log(nidd)- log(eidd))) Gdjd <- 2 * sum(ndjd * (log(ndjd)- log(edjd))) Gddk <- 2 * sum(nddk * (log(nddk)- log(eddk))) # for the 2-way interactions Gijd <- 2 * sum(nijd * (log(nijd)- log(eijd))) Gidk <- 2 * sum(nidk * (log(nidk)- log(eidk))) Gdjk <- 2 * sum(ndjk * (log(ndjk)- log(edjk))) # for the 3-way interactions Gijk <- 2 * sum(nijk * (log(nijk)- log(eijk))) # Fifth, the correction factor (Williams, 1976) for each factor c1 <- 1+ ((A)^2-1)/ ( 6 * (A-1) * nddd) c2 <- 1+ ((B)^2-1)/ ( 6 * (B-1) * nddd) c3 <- 1+ ((C)^2-1)/ ( 6 * (C-1) * nddd) c12 <- 1+ ((A*B)^2-1)/ ( 6 * (A-1) * (B-1) * nddd) c13 <- 1+ ((A*C)^2-1)/ ( 6 * (A-1) * (C-1) * nddd) c23 <- 1+ ((B*C)^2-1)/ ( 6 * (B-1) * (C-1) * nddd) c123 <- 1+ ((A*B*C)^2-1)/ ( 6 * (A-1) * (B-1) * (C-1) * nddd) # Finally, getting the p-values for each corrected effect pidd = 1- pchisq(Gidd/ c1, df = A-1) pdjd = 1- pchisq(Gdjd/ c2, df = B-1) pddk = 1- pchisq(Gddk/ c3, df = C-1) pijd = 1- pchisq(Gijd/ c12, df = (A-1)*(B-1) ) pidk = 1- pchisq(Gidk/ c13, df = (A-1)*(C-1) ) pdjk = 1- pchisq(Gdjk/ c23, df = (B-1)*(C-1) ) pijk = 1- pchisq(Gijk/ c123, df = (A-1)*(B-1)*(C-1)) # assembling the results in a table results <- data.frame( G = c(Gtotal, Gidd, Gdjd, Gddk, Gijd, Gidk, Gdjk, Gijk), df = c(A*B*C-1, A-1, B-1, C-1, (A-1)*(B-1), (A-1)*(C-1), (B-1)*(C-1), (A-1)*(B-1)*(C-1) ), Gcorrected = c(NA, Gidd/c1, Gdjd/c2, Gddk/c3, Gijd/c12, Gidk/c13, Gdjk/c23, Gijk/c123 ), pvalue = c( NA, pidd, pdjd, pddk, pijd, pidk, pdjk, pijk), etasq = c( NA, anofaES(nidd/nddd), anofaES(ndjd/nddd), anofaES(nddk/nddd), anofaES(nijd/nddd), anofaES(nidk/nddd), anofaES(ndjk/nddd), anofaES(nijk/nddd) ) ) by2 <-lapply(combn(factors,2,simplify=FALSE), function(x) paste(x, collapse=":")) rownames(results) <-c("Total", factors, by2, paste(factors, collapse=":")) return( list( list(A, B, C), clevels, results )) } anofa4way <- function(dataC, freq, factors ) { # First, we determine the number of levels for each factors A <- length(unique(dataC[[factors[1]]])) B <- length(unique(dataC[[factors[2]]])) C <- length(unique(dataC[[factors[3]]])) D <- length(unique(dataC[[factors[4]]])) # Second, we compute the grand total and the marginal frequencies in n variables # The factors are noted with the letters i, j, k and l # In this notation, "d" denotes the dot. ndddd <- sum(dataC[[freq]]) # first-order marginals niddd <- aggregate(as.formula(paste(freq, factors[1], sep="~")), data = dataC, sum)[[freq]] ndjdd <- aggregate(as.formula(paste(freq, factors[2], sep="~")), data = dataC, sum)[[freq]] nddkd <- aggregate(as.formula(paste(freq, factors[3], sep="~")), data = dataC, sum)[[freq]] ndddl <- aggregate(as.formula(paste(freq, factors[4], sep="~")), data = dataC, sum)[[freq]] # second-order marginals by2 <-lapply(combn(factors,2,simplify=FALSE), function(x) paste(x, collapse=" + ")) nijdd <- matrix(aggregate(as.formula(paste(freq, by2[[1]],sep="~")), data = dataC, sum)[[freq]], A) nidkd <- matrix(aggregate(as.formula(paste(freq, by2[[2]],sep="~")), data = dataC, sum)[[freq]], A) niddl <- matrix(aggregate(as.formula(paste(freq, by2[[3]],sep="~")), data = dataC, sum)[[freq]], A) ndjkd <- matrix(aggregate(as.formula(paste(freq, by2[[4]],sep="~")), data = dataC, sum)[[freq]], B) ndjdl <- matrix(aggregate(as.formula(paste(freq, by2[[5]],sep="~")), data = dataC, sum)[[freq]], B) nddkl <- matrix(aggregate(as.formula(paste(freq, by2[[6]],sep="~")), data = dataC, sum)[[freq]], C) # third-order marginals by3 <-lapply(combn(factors,3,simplify=FALSE), function(x) paste(x, collapse=" + ")) nijkd <- array(aggregate(as.formula(paste(freq, by3[[1]],sep="~")), data = dataC, sum)[[freq]], c(A,B,C)) nijdl <- array(aggregate(as.formula(paste(freq, by3[[2]],sep="~")), data = dataC, sum)[[freq]], c(A,B,D)) nidkl <- array(aggregate(as.formula(paste(freq, by3[[3]],sep="~")), data = dataC, sum)[[freq]], c(A,C,D)) ndjkl <- array(aggregate(as.formula(paste(freq, by3[[4]],sep="~")), data = dataC, sum)[[freq]], c(B,C,D)) # and finally the observed frequencies in a matrix nijkl <- array((temp<-aggregate(as.formula(paste(freq, paste(factors, collapse="*"),sep="~")), data = dataC, sum))[[freq]],c(A,B,C,D)) clevels <- list(as.character(unique(temp[[factors[[1]]]])), as.character(unique(temp[[factors[[2]]]])), as.character(unique(temp[[factors[[3]]]])), as.character(unique(temp[[factors[[4]]]])) ) # Third, we computed the expected frequencies e edddd <- ndddd / (A * B * C * D) # first-order expectation eiddd <- rep(ndddd / A, A) edjdd <- rep(ndddd / B, B) eddkd <- rep(ndddd / C, C) edddl <- rep(ndddd / D, D) # second-order expectation eijdd <- outer(niddd, ndjdd)/ndddd eidkd <- outer(niddd, nddkd)/ndddd eiddl <- outer(niddd, ndddl)/ndddd edjkd <- outer(ndjdd, nddkd)/ndddd edjdl <- outer(ndjdd, ndddl)/ndddd eddkl <- outer(nddkd, ndddl)/ndddd # third-order expectation (there might be a matrix operation for that?) eijkd <- array(NA, c(A,B,C)) for(i in 1:A) for(j in 1:B) for(k in 1:C) { eijkd[i,j,k] <- ndddd * nijdd[i,j] * nidkd[i,k] * ndjkd[j,k] /(niddd[i] * ndjdd[j] * nddkd[k] ) } eijdl <- array(NA, c(A,B,D)) for(i in 1:A) for(j in 1:B) for(l in 1:D) { eijdl[i,j,l] <- ndddd * nijdd[i,j] * niddl[i,l] * ndjdl[j,l] /(niddd[i] * ndjdd[j] * ndddl[l] ) } eidkl <- array(NA, c(A,C,D)) for(i in 1:A) for(k in 1:C) for(l in 1:D) { eidkl[i,k,l] <- ndddd * nidkd[i,k] * niddl[i,l] * nddkl[k,l] /(niddd[i] * nddkd[k] * ndddl[l] ) } edjkl <- array(NA, c(B,C,D)) for(j in 1:B) for(k in 1:C) for(l in 1:D) { edjkl[j,k,l] <- ndddd * ndjkd[j,k] * ndjdl[j,l] * nddkl[k,l] /(ndjdd[j] * nddkd[k] * ndddl[l] ) } # forth-order expectation (there might be a matrix operation for that?) eijkl <- array(NA, c(A,B,C,D)) for(i in 1:A) for(j in 1:B) for(k in 1:C) for(l in 1:D) { eijkl[i,j,k,l] <- 1/ndddd * ( niddd[i] * ndjdd[j] * nddkd[k] * ndddl[l] * nijkd[i,j,k] * nijdl[i,j,l] * nidkl[i,k,l] * ndjkl[j,k,l] ) / ( nijdd[i,j] * nidkd[i,k] * niddl[i,l] * ndjkd[j,k] * ndjdl[j,l] * nddkl[k,l] ) } # Fourth, get the G statistics Gtotal <- 2 * sum(sum(sum(sum(nijkl * (log(nijkl)- log(edddd)))))) # for the main effects Giddd <- 2 * sum(niddd * (log(niddd)- log(eiddd))) Gdjdd <- 2 * sum(ndjdd * (log(ndjdd)- log(edjdd))) Gddkd <- 2 * sum(nddkd * (log(nddkd)- log(eddkd))) Gdddl <- 2 * sum(ndddl * (log(ndddl)- log(edddl))) # for the 2-way interactions Gijdd <- 2 * sum(nijdd * (log(nijdd)- log(eijdd))) Gidkd <- 2 * sum(nidkd * (log(nidkd)- log(eidkd))) Giddl <- 2 * sum(niddl * (log(niddl)- log(eiddl))) Gdjkd <- 2 * sum(ndjkd * (log(ndjkd)- log(edjkd))) Gdjdl <- 2 * sum(ndjdl * (log(ndjdl)- log(edjdl))) Gddkl <- 2 * sum(nddkl * (log(nddkl)- log(eddkl))) # for the 3-way interactions Gijkd <- 2 * sum(nijkd * (log(nijkd)- log(eijkd))) Gijdl <- 2 * sum(nijdl * (log(nijdl)- log(eijdl))) Gidkl <- 2 * sum(nidkl * (log(nidkl)- log(eidkl))) Gdjkl <- 2 * sum(ndjkl * (log(ndjkl)- log(edjkl))) # and the 4-way interaction Gijkl <- 2 * sum(nijkl * (log(nijkl)- log(eijkl))) # Fifth, the correction factor (Williams, 1976) for each factor c1 <- 1+ ((A)^2-1)/ ( 6 * (A-1) * ndddd) c2 <- 1+ ((B)^2-1)/ ( 6 * (B-1) * ndddd) c3 <- 1+ ((C)^2-1)/ ( 6 * (C-1) * ndddd) c4 <- 1+ ((D)^2-1)/ ( 6 * (D-1) * ndddd) c12 <- 1+ ((A*B)^2-1)/ ( 6 * (A-1) * (B-1) * ndddd) c13 <- 1+ ((A*C)^2-1)/ ( 6 * (A-1) * (C-1) * ndddd) c14 <- 1+ ((A*D)^2-1)/ ( 6 * (A-1) * (D-1) * ndddd) c23 <- 1+ ((B*C)^2-1)/ ( 6 * (B-1) * (C-1) * ndddd) c24 <- 1+ ((B*D)^2-1)/ ( 6 * (B-1) * (D-1) * ndddd) c34 <- 1+ ((C*D)^2-1)/ ( 6 * (C-1) * (D-1) * ndddd) c123 <- 1+ ((A*B*C)^2-1)/ ( 6 * (A-1) * (B-1) * (C-1) * ndddd) c124 <- 1+ ((A*B*D)^2-1)/ ( 6 * (A-1) * (B-1) * (D-1) * ndddd) c134 <- 1+ ((A*C*D)^2-1)/ ( 6 * (A-1) * (C-1) * (D-1) * ndddd) c234 <- 1+ ((B*C*D)^2-1)/ ( 6 * (B-1) * (C-1) * (D-1) * ndddd) c1234 <- 1+ ((A*B*C*D)^2-1)/ ( 6 * (A-1) * (B-1) * (C-1) * (D-1) * ndddd) # Finally, getting the p-values for each corrected effect piddd = 1- pchisq(Giddd/ c1, df = A-1) pdjdd = 1- pchisq(Gdjdd/ c2, df = B-1) pddkd = 1- pchisq(Gddkd/ c3, df = C-1) pdddl = 1- pchisq(Gdddl/ c4, df = D-1) pijdd = 1- pchisq(Gijdd/ c12, df = (A-1)*(B-1) ) pidkd = 1- pchisq(Gidkd/ c13, df = (A-1)*(C-1) ) piddl = 1- pchisq(Giddl/ c14, df = (A-1)*(D-1) ) pdjkd = 1- pchisq(Gdjkd/ c23, df = (B-1)*(C-1) ) pdjdl = 1- pchisq(Gdjdl/ c24, df = (B-1)*(D-1) ) pddkl = 1- pchisq(Gddkl/ c34, df = (C-1)*(D-1) ) pijkd = 1- pchisq(Gijkd/ c123, df = (A-1)*(B-1)*(C-1)) pijdl = 1- pchisq(Gijdl/ c124, df = (A-1)*(B-1)*(D-1)) pidkl = 1- pchisq(Gidkl/ c134, df = (A-1)*(C-1)*(D-1)) pdjkl = 1- pchisq(Gdjkl/ c234, df = (B-1)*(C-1)*(D-1)) pijkl = 1- pchisq(Gijkl/ c1234, df = (A-1)*(B-1)*(C-1)*(D-1) ) # assembling the results in a table results <- data.frame( G = c(Gtotal, Giddd, Gdjdd, Gddkd, Gdddl, Gijdd, Gidkd, Giddl, Gdjkd, Gdjdl, Gddkl, Gijkd, Gijdl, Gidkl, Gdjkl, Gijkl), df = c(A*B*C*D-1, A-1, B-1, C-1, D-1, (A-1)*(B-1), (A-1)*(C-1), (A-1)*(D-1),(B-1)*(C-1),(B-1)*(D-1),(C-1)*(D-1), (A-1)*(B-1)*(C-1), (A-1)*(B-1)*(D-1), (A-1)*(C-1)*(D-1),(B-1)*(C-1)*(D-1), (A-1)*(B-1)*(C-1)*(D-1) ), Gcorrected = c(NA, Giddd/c1, Gdjdd/c2, Gddkd/c3, Gdddl/c4, Gijdd/c12, Gidkd/c13, Giddl/c14, Gdjkd/c23, Gdjdl/c24, Gddkl/c34, Gijkd/c123, Gijdl/c124, Gidkl/c124, Gdjkl/c234, Gijkl/c1234), pvalue = c(NA, piddd, pdjdd, pddkd, pdddl, pijdd, pidkd, piddl, pdjkd, pdjdl, pddkl, pijkd, pijdl, pidkl, pdjkl, pijkl), etasq = c(NA, anofaES(niddd/ndddd), anofaES(ndjdd/ndddd), anofaES(nddkd/ndddd), anofaES(ndddl/ndddd), anofaES(nijdd/ndddd), anofaES(nidkd/ndddd), anofaES(niddl/ndddd), anofaES(ndjkd/ndddd), anofaES(ndjdl/ndddd), anofaES(nddkl/ndddd), anofaES(nijkd/ndddd), anofaES(nijdl/ndddd), anofaES(nidkl/ndddd), anofaES(ndjkl/ndddd), anofaES(nijkl/ndddd) ) ) by2 <-lapply(combn(factors,2,simplify=FALSE), function(x) paste(x, collapse=":")) by3 <-lapply(combn(factors,3,simplify=FALSE), function(x) paste(x, collapse=":")) rownames(results) <-c("Total", factors, by2, by3, paste(factors, collapse=":")) return( list( list(A, B, C, D), clevels, results )) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-anofa.R
###################################################################################### #' @title contrastFrequencies: contrasts analysis of frequency data. #' #' @md #' #' @description The function `contrastFrequencies()` performs contrasts analyses #' of frequencies after an omnibus analysis has been obtained with `anofa()` #' according to the ANOFA framework. See \insertCite{lc23b;textual}{ANOFA} for more. #' #' @param w An ANOFA object obtained from `anofa()` or `emFrequencies()`; #' #' @param contrasts A list that gives the weights for the contrasts to analyze. #' The contrasts within the list can be given names to distinguish them. #' The contrast weights must sum to zero and their cross-products must equal 0 #' as well. #' #' @return a model fit of the constrasts. #' #' @details contrastFrequencies computes the Gs for the contrasts, #' testing the hypothesis that it equals zero. #' The contrasts are each 1 degree of freedom, and the sum of the contrasts' #' degrees of freedom totalize the effect being decomposed. #' #' @references #' \insertAllCited{} #' #' @examples #' # Basic example using a two-factors design with the data in compiled format. #' # Ficticious data present frequency of observation classified according #' # to Intensity (three levels) and Pitch (two levels) for 6 possible cells. #' minimalExample #' #' # performs the omnibus analysis first (mandatory): #' w <- anofa(Frequency ~ Intensity * Pitch, minimalExample) #' summary(w) #' #' # execute the simple effect of Pitch for every levels of Intensity #' e <- emFrequencies(w, ~ Intensity | Pitch) #' summary(e) #' #' # For each Pitch, contrast the three intensities, first #' # by comparing the first two levels to the third, second #' # by comparing the first to the second level: #' w3 <- contrastFrequencies( e, list( #' contrast1 = c(1, 1, -2)/2, #' contrast2 = c(1, -1, 0) ) #' ) #' summary(w3) #' #' # Example using the Landis et al. (2013) data, a 3 x 5 design involving #' # program of care (3 levels) and provider of care (5 levels). #' LandisBarrettGalvin2013 #' #' # performs the omnibus analysis first (mandatory): #' w <- anofa(obsfreq ~ provider * program, LandisBarrettGalvin2013) #' summary(w) #' #' # execute the simple effect of Pitch for every levels of Intensity #' e <- emFrequencies(w, ~ program | provider) #' summary(e) #' #' # For each Pitch, contrast the three intensities, first #' # by comparing the first two levels to the third, second #' # by comparing the first to the second level: #' w3 <- contrastFrequencies( e, list( #' contrast1 = c(1, 1, -2)/2, #' contrast2 = c(1, -1, 0) ) #' ) #' summary(w3) #' #' ###################################################################################### #' #' @export contrastFrequencies # ###################################################################################### contrastFrequencies <- function( w = NULL, contrasts = NULL ){ ############################################################################## ## STEP 1: VALIDATION OF INPUT ############################################################################## # 1.1: Is w of the right type if (!("ANOFAobject" %in% class(w))) stop("ANOFA::error(31): The argument w is not an ANOFA object. Exiting...") # 1.2: Are the contrasts of the right length if (min(unlist(lapply(contrasts, length))) != max(unlist(lapply(contrasts, length)))) stop("ANOFA::error(32): The constrasts have differing lengths. Exiting...") relevantlevels = prod(if (w$type == "ANOFAomnibus") { w$nlevels } else { w$nlevels[w$factColumns %in% w$subFactors] } ) if (!(all(unlist(lapply(contrasts, length)) == relevantlevels ))) stop("ANOFA::error(33): The contrats lengths does not match the number of levels. Exiting...") # 1.3: Are the contrasts legitimate (a) sum to zero; if (!(all(round(unlist(lapply(contrasts,sum)),8)==0))) stop("ANOFA::error(34): Some of the constrats do not sum to 0. Exiting...") # 1.3: Are the contrasts legitimate (b) cross-product sum to zero sums = c() for (i in names(contrasts)) {for (j in setdiff(names(contrasts), i)) { sums <-append(sums, round(sum(contrasts[[i]]*contrasts[[j]]) ),8) } } if (!(all(sums == 0))) stop("ANOFA::error(35): Some of the cross-products of contrasts do not totalize 0. Exiting...") # 1.3: Are the contrasts legitimate (c) all oppositions sum to 1 if (!(all(round(unlist(lapply(contrasts, \(x) sum(abs(x)))),8)==2))) stop("ANOFA::error(36): Some of the contrasts' weigth does not equal 1 (for the positive weights) or -1 (for the negative weights). Exiting...") # 1.4: is there an acceptable number of contrasts if (length(contrasts) > relevantlevels-1) stop("ANOFA::error(37): There are more contrasts defined than degrees of freedom. Exiting...") ############################################################################## ## STEP 2: Run the analysis ############################################################################## # 2.1: identify the factors # 2.2: perform the analysis based on ??? analysis <- if(w$type == "ANOFAomnibus") { ## Contrasts on the full design cst1way(w$compiledData, w$freqColumn, contrasts) } else { # "ANOFAsimpleeffects" ## Contrasts on sub-data based on nesting factor(s) cstMway(w$compiledData, w$freqColumn, w$subFactors, w$nestedFactors, contrasts) } ############################################################################## # STEP 3: Return the object ############################################################################## # 3.1: preserve everything in an object of class ANOFAobject res <- list( type = "ANOFAcontrasts", formula = as.formula(w$formula), compiledData = w$compiledData, freqColumn = w$freqColumn, factColumns = w$factColumns, nlevels = w$nlevels, clevels = w$clevels, # new information added results = analysis ) class(res) <- c("ANOFAobject", class(res) ) return( res ) } # ################################################################ # # Lets run the orthogonal contrasts # # ################################################################ # there is only two possible cases: # a) the contrasts are on the full data ==> cst1way # b) the contrasts are nested with some factor(s) ==> cstMway cst1way <- function(dataC, freqcol, contrasts) { # extract the frequencies and the total frequency ns <- dataC[[freqcol]] nd <- sum(ns) # get the G statistics for each contrast Gs <- c() for (i in contrasts) { Gs <- c(Gs, 2 * sum( contrastObsd(i, ns) * ( log( contrastObsd(i, ns) ) - log( contrastNull(i, ns) ) ) ) ) } # compute the correction factor cf cf <- 1+ (length(ns)^2-1) / ( 6 * (length(ns)-1) * nd) # compute the p values on the corrected G as usual pcontrasts <- 1- pchisq(Gs/ cf, df = 1) # This is it! let's put the results in a table resultsGContrasts <- data.frame( G = Gs, df = rep(1, length(Gs)), Gcorrected = c(Gs/ cf), pvalue = pcontrasts ) rownames(resultsGContrasts) <- names(contrasts) resultsGContrasts } cstMway <- function(datasC, freqcol, subfact, nestfact, contrasts) { ## run cst1way on every levels of the nesting factor(s) splitting <- paste(nestfact, collapse = "+") dtas <- split(datasC, as.formula(paste("~",splitting))) # in case other factors are not named, collapse over these frm <- paste(freqcol, paste(subfact, collapse = "+"), sep=" ~ ") dtas <- lapply(dtas, \(x) aggregate(x, as.formula(frm), sum)) Gs <- data.frame() for (i in names(dtas)) { subGs <- cst1way( dtas[[i]], freqcol, contrasts) rownames(subGs) <- paste( rownames(subGs), i, sep=" | ") Gs <- rbind(Gs, subGs) } Gs } # ################################################################ # # Sub-functions to get observed and expected frequencies # # ################################################################ # the null hypothesis for the conditions implicated in the contrast # ns is a vector contrastNull <- function(contrast, ns) { pp <- sign(abs(contrast)) pp <- pp * sum(ns * pp)/sum(pp) + (1 - pp) * ns pp[contrast!=0] } # the contrast hypothesis for the conditions implicated in the contrast # ns is a vector contrastObsd <- function(contrast, ns) { nn <- rep(0, length(ns) ) ss <- contrast ss[sign(contrast)<=0] <- 0 nn <- nn + sign(abs(ss)) * sum(ns * ss) ss <- -contrast ss[sign(contrast)>=0] <- 0 nn <- nn + sign(abs(ss)) * sum(ns * ss) ss <- contrast ss[sign(contrast)==0] <- 1 ss[sign(contrast)!=0] <- 0 nn <- nn + sign(abs(ss)) * sum(ns * ss) nn[contrast!=0] }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-contrastFrequencies.R
################################################################################### #' @name conversion #' #' @title Converting between formats #' #' @aliases toWide toLong toCompiled toRaw toTabular #' #' @md #' #' @description The functions `toWide()`, `toLong()`, `toCompiled()` #' `toRaw()` and `toTabular()` #' converts the data into various formats. #' #' @usage toWide(w) #' @usage toLong(w) #' @usage toCompiled(w) #' @usage toRaw(w) #' @usage toTabular(w) #' #' @param w An instance of an ANOFA object. #' #' @return a data frame in the requested format. #' #' @details The classification of a set of $n$ participants can be #' given using many formats. One basic format (called `wide` herein) #' has $n$ lines, one per participants, and category names assigned #' to each. #' Another format (called `compiled` herein) is to have a list of all #' the categories and the number of participants falling in each #' cells. This last format is typically much more compact (if there #' are 6 categories, the data are all contained in six lines). #' However, we fail to see each individual contributing to the counts. #' See the vignette DataFormatsForFrequencies for more. #' A third possible format (called `raw` herein) put one column per #' category and 1 is the observation matches this category, 0 otherwise. #' This format results in $n$ lines, one participants, and as many #' columns are there are categories. #' Lastly, a fourth format (called `long` herein) as, on a line, the #' factor name and the category assigned in that factor. If there are #' $f$ factors and $n$ participants, the data are in $f*n$ lines. #' #' @details See the vignette DataFormatsForFrequencies for more. #' #' @examples #' #' # The minimalExample contains $n$ of 20 participants categorized according #' # to two factors $f = 2$, namely `Intensity` (three levels) #' # and Pitch (two levels) for 6 possible cells. #' minimalExample #' #' # Lets incorporate the data in an anofa data structure #' w <- anofa( Frequency ~ Intensity * Pitch, minimalExample ) #' #' # The data presented using various formats looks like #' toWide(w) #' # ... has 20 lines ($n$) and 2 columns ($f$) #' #' toLong(w) #' # ... has 40 lines ($n \times f$) and 3 columns (participant's `Id`, `Factor` name and `Level`) #' #' toRaw(w) #' # ... has 20 lines ($n$) and 5 columns ($2+3$) #' #' toCompiled(w) #' # ... has 6 lines ($2 \times 3$) and 3 columns ($f$ + 1) #' #' toTabular(w) #' # ... has one table with $2 \times 3$ cells. If there had been #' # more than two factors, the additional factor(s) would be on distinct layers. #' ################################################################################### #' #' @export toWide #' @export toLong #' @export toRaw #' @export toCompiled #' @export toTabular #' @importFrom utils tail # ################################################################################### toWide <- function( w = NULL ) { # is w of class ANOFA.object? if (!("ANOFAobject" %in% class(w) )) stop("ANOFA::error(101): argument is not an ANOFA generated object. Exiting...") return( ctow(w$compiledData, w$freqColumn) ) } toLong <- function( w = NULL ) { # is w of class ANOFA.object? if (!("ANOFAobject" %in% class(w) )) stop("ANOFA::error(102): argument is not an ANOFA generated object. Exiting...") return( ctol(w$compiledData, w$freqColumn) ) } toRaw <- function( w = NULL ) { # is w of class ANOFA.object? if (!("ANOFAobject" %in% class(w) )) stop("ANOFA::error(103): argument is not an ANOFA generated object. Exiting...") return( ctor(w$compiledData, w$freqColumn) ) } toCompiled <- function( w = NULL ) { # is w of class ANOFA.object? if (!("ANOFAobject" %in% class(w) )) stop("ANOFA::error(104): argument is not an ANOFA generated object. Exiting...") return( w$compiledData ) # nothing to do, the data are internally stored in compiled form } toTabular <- function( w = NULL ) { # is w of class ANOFA.object? if (!("ANOFAobject" %in% class(w) )) stop("ANOFA::error(105): argument is not an ANOFA generated object. Exiting...") return( ctot(w$compiledData, w$freqColumn) ) } ################################################################################### ### CONVERSIONS from compiled to ... ################################################################################### # compiled => wide DONE ctow <- function(x, f) { y <- x[,names(x)!=f, drop=FALSE] as.data.frame(lapply(y, rep, x[[f]])) } # compiled => raw DONE ctor <- function(x, f) { dummy.coding <- function(x){ 1 * sapply(unique(x), USE.NAMES = TRUE, FUN = function(v) {x == v}) } res <- do.call("cbind", apply(ctow(x,f), 2, dummy.coding, simplify=FALSE)) data.frame(res) } # compiled => long DONE ctol <- function(x, f) { #ANOFA.Id <<- 0 ## global variable assign('ANOFA.Id', 0, ANOFA.env) ## global variable line.coding <-function(ln) { assign('ANOFA.Id', ANOFA.env$ANOFA.Id + 1, ANOFA.env) data.frame( Id = rep(ANOFA.env$ANOFA.Id, length(ln)), Factor = names(ln), Level = as.character(unlist(ln)) ) } do.call("rbind", apply(ctow(x, f), 1, line.coding ) ) } # compiled => tabular DONE ctot <- function(x, f) { table(ctow(x, f)) } ################################################################################### ### CONVERSIONS from ... to compiled ################################################################################### # These functions are hidden, but used in importing the data into anofa() # tabular => compiled DONE ttoc <- function(x, f) { res <- expand.grid(dimnames(x)) res[[f]] <- c(x) return(res) } # wide => compiled DONE wtoc <- function(x, f) { # https://stackoverflow.com/a/53775768/5181513 res <- aggregate(f ~ ., transform(x, f = 1), FUN = sum) colnames(res)[which(names(res) == "f")] <- f res } # long => wide DONE ltow <- function(x, frm){ if (!has.nested.terms(frm)) stop("ANOFA:error: equation is not given with a nested term |. Exiting...") nestingvar <- sub.formulas(frm, "|")[[1]][[3]] nestedvar <- sub.formulas(frm,"|")[[1]][[2]] if (length(all.vars(nestingvar))!=1) stop("ANOFA::error(105): the nesting term is composed of more than one variable. Exiting...") if (length(all.vars(nestedvar))!=1) stop("ANOFA::error(106): the nested factor is composed of more than one variable. Exiting...") ids <- unique(x[[nestingvar]]) # for each participant res = data.frame() for (i in ids) { temp <- x[x[[nestingvar]] == i,] rownames(temp) <- temp[[nestedvar]] temp <- tail(t(temp),-2) rownames(temp) <- NULL res = rbind(res, data.frame(temp)) } return(res) } # long => compiled DONE ltoc <- function(x, f, frm) { wtoc(ltow(x, frm), f) } # raw => wide DONE rtow <- function(x, frm, fact = NULL) { if (!has.cbind.terms(frm)) stop("ANOFA:error(107): equation is not given with cbind. Exiting...") # extract sub.formulas for all terms res <- sub.formulas( frm, "cbind" ) if (!(is.null(fact))) { if (length(fact)!= length(res)) stop("ANOFA::error(108): The number of factors given does not correspond to the number of cbind in the formula. Exiting...") } else { fact <- LETTERS[1:length(res)] } # get all.vars(%) for each cols <- lapply(res, function(x) all.vars(x)) # set factor names if none provided # répéter pour tous avec le nom? df <- data.frame( Id = 1:dim(x)[1] ) for (i in 1:length(fact)) { onesetofcols <- x[,cols[[i]]] df[[fact[i]]] <- apply(onesetofcols, 1, function(x) colnames(onesetofcols)[x==1]) } df$Id = NULL return(df) } # raw => compiled DONE rtoc <- function(x, f, frm, fact = NULL ) { wtoc(rtow(x, frm, fact), f) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-convert.R
###################################################################################### #' @title Computing effect size within the ANOFA. #' #' @md #' #' @description The function `anofaES()` compute effect size from observed frequencies #' according to the ANOFA framework. See \insertCite{lc23b;textual}{ANOFA} for more. #' #' @usage anofaES( props ) #' #' @param props the expected proportions; #' #' @return The predicted effect size from a population with the given proportions. #' #' @details The effect size is given as an eta-square. #' #' @references #' \insertAllCited{} #' #' @examples #' # if we assume the following proportions: #' pred <- c(.35, .25, .25, .15) #' #' # then eta-square is given by #' anofaES( pred ) #' ###################################################################################### #' #' @export anofaES # ###################################################################################### anofaES <- function( props ){ ############################################################################## ## STEP 1: VALIDATION OF INPUT ############################################################################## # 1.1 proportions must totalize 1.00 if (round(sum(props),4)!=1) { warning("ANOFA::error(41): The proportions do not totalize 1.00 (100%). Standardizing...") props <- props / sum(props) } ############################################################################## ## STEP 2: MAKES THE COMPUTATION ############################################################################## P <- length(props) f2 <- 2 * sum(props * log(P * props) ) eta2 <- f2 / (1 + f2) eta2 }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-effectsize.R
###################################################################################### #' @title emFrequencies: simple effect analysis of frequency data. #' #' @md #' #' @description The function `emFrequencies()` performs a simple effect analyses #' of frequencies after an omnibus analysis has been obtained with `anofa()` #' according to the ANOFA framework. See \insertCite{lc23b;textual}{ANOFA} for more. #' #' @usage emFrequencies(w, formula) #' #' @param w An ANOFA object obtained from `anofa()`; #' #' @param formula A formula which indicates what simple effect to analyze. #' only one simple effect formula at a time can be analyzed. The formula #' is given using a vertical bar, e.g., " ~ factorA | factorB " to obtain #' the effect of Factor A within every level of the Factor B. #' #' @return a model fit of the simple effect. #' #' @details emFrequencies computes expected marginal frequencies and #' analyze the hypothesis of equal frequencies. #' The sum of the Gs of the simple effects are equal to the #' interaction and main effect Gs, as this is an additive decomposition #' of the effects. #' #' @references #' \insertAllCited{} #' #' @examples #' # Basic example using a two-factors design with the data in compiled format. #' # Ficticious data present frequency of observation classified according #' # to Intensity (three levels) and Pitch (two levels) for 6 possible cells. #' minimalExample #' #' # performs the omnibus analysis first (mandatory): #' w <- anofa(Frequency ~ Intensity * Pitch, minimalExample) #' summary(w) #' #' # execute the simple effect of Pitch for every levels of Intensity #' e <- emFrequencies(w, ~ Pitch | Intensity) #' summary(e) #' #' # As a check, you can verify that the Gs are decomposed additively #' sum(e$results[,1]) #' w$results[3,1]+w$results[4,1] #' #' # Real-data example using a two-factor design with the data in compiled format: #' LandisBarrettGalvin2013 #' #' w <- anofa( obsfreq ~ provider * program, LandisBarrettGalvin2013) #' anofaPlot(w) #' summary(w) #' #' # there is an interaction, so look for simple effects #' e <- emFrequencies(w, ~ program | provider ) #' summary(e) #' #' # Example from Gillet1993 : 3 factors for appletrees #' Gillet1993 #' #' w <- anofa( Freq ~ species * location * florished, Gillet1993) #' e <- emFrequencies(w, ~ florished | location ) #' #' # Again, as a check, you can verify that the Gs are decomposed additively #' w$results[4,1]+w$results[7,1] # B + B:C #' sum(e$results[,1]) #' #' # You can ask easier outputs with #' summarize(w) # or summary(w) for the ANOFA table only #' explain(w) # human-readable ouptut ((pending)) #' ###################################################################################### #' #' @export emFrequencies #' @importFrom utils capture.output # ###################################################################################### emFrequencies <- function( w = NULL, formula = NULL ){ ############################################################################## ## STEP 1: VALIDATION OF INPUT ############################################################################## # 1.1 Is w of the right type and having more than 1 factor if (!("ANOFAobject" %in% class(w))) stop("ANOFA::error(21): The argument w is not an ANOFA object. Exiting...") if (length(w$factColumns)==1) stop("ANOFA::error(22): There must be at least two factors in the design. Exiting...") # 1.2 If formula indeed a formula if (!(is.formula(formula))) stop("ANOFA::error(23): The formula argument is not a legitimate formula. Exiting...") # 1.3 Is the rhs having a | sign, and only one if (!(has.nested.terms(formula))) stop("ANOFA::error(24): The rhs of formula must have a variable nested within another variable. Exiting... ") if (length(tmp <- sub.formulas(formula, "|"))!=1) stop("ANOFA::error(25): The rhs of formula must contain a single nested equation. Exiting...") if (tmp[[1]][[2]]==tmp[[1]][[3]]) stop("ANOFA::error(26): The two variables on either side of | must differ. Exiting...") # 1.4 If the dependent variable is named (optional), is it the correct variable if (length(formula)==3) { if (formula[[2]] != w$freqColumn) stop("ANOFA::error(27): The lhs of formula is not the correct frequency variable. Exiting...") } # 1.5 Are the factors named in formula present in w vars <- all.vars(formula) # extract variables in cbind and with | alike if (!(all(vars %in% names(w$compiledData)))) stop("ANOFA::error(28): variables in `formula` are not all in the data. Exiting...") ############################################################################## ## STEP 2: Run the analysis based on the number of factors ############################################################################## # 2.1: identify the factors subfactors <- all.vars(tmp[[1]][[2]]) nestfactor <- all.vars(tmp[[1]][[3]]) # 2.2: perform the analysis based on the number of factors analysis <- switch( length(subfactors), emf1way(w, subfactors, nestfactor), emf2way(w, subfactors, nestfactor), emf3way(w, subfactors, nestfactor), ) ############################################################################## # STEP 3: Return the object ############################################################################## # 3.1: preserve everything in an object of class ANOFAobject res <- list( type = "ANOFAsimpleeffects", formula = as.formula(w$formula), compiledData = w$compiledData, freqColumn = w$freqColumn, factColumns = w$factColumns, nlevels = w$nlevels, clevels = w$clevels, # new information added formulasimple = as.formula(formula), nestedFactors = nestfactor, subFactors = subfactors, nestedLevels = dim(analysis)[1], results = analysis ) class(res) <- c("ANOFAobject", class(res) ) return( res ) } emf1way <- function(w, subfact, nestfact){ ## Herein, the sole factor analyzed is called factor A, which is nested within factor B, ## that is, the effect of A within b1, the effect of A within b2, ... A within bj. ## There can only be a single nesting variable (e.g., B) ## We can get here if (a) there are 2 factors, (b) there are 3 factors, (c) there are 4 factors # The factors position in the factor list and their number of levels posA <- (1:length(w$factColumns))[w$factColumns==subfact] A <- w$nlevels[posA] # posB <- (1:length(w$factColumns))[w$factColumns==nestfact] # B <- w$nlevels[posB] if (length(nestfact)==1) { posB <- (1:length(w$nlevels))[w$factColumns==nestfact] B <- w$nlevels[posB] lvls <- w$clevels[[posB]] } else { B <-1 lvls <- c() for (i in nestfact) { pos <- (1:length(w$nlevels))[w$factColumns==i] B <- B * w$nlevels[pos] lvls <- unlist(lapply(w$clevels[[pos]], function(x) paste(lvls,x, sep=":"))) } nestfact <- paste(nestfact, collapse = "+") } # the total n and the vector marginals ndd <- sum(w$compiledData[[w$freqColumn]]) ndj <- aggregate(as.formula(paste(w$freqColumn, nestfact, sep="~")), data = w$compiledData, sum)[[w$freqColumn]] by2 <- paste(c(nestfact, subfact), collapse=" + ") nij <- matrix(aggregate(as.formula(paste(w$freqColumn, by2, sep="~")), data = w$compiledData, sum)[[w$freqColumn]], B) # First, we compute the expected frequencies e separately for each levels of factor B eigivenj <- ndj / A # Second, we get the G statistics for each level Gs <- c() for (j in 1:B) { Gs[j] <- 2 * sum(nij[j,] * (log(nij[j,])- log(eigivenj[j]))) } # Third, the correction factor (Williams, 1976) for each cf <- 1+ (A^2-1) / ( 6 * (A-1) * ndd) # Finally, getting the p-values for each corrected effect ps = 1- pchisq( Gs / cf, df = B-1) # This is it! let's put the results in a table resultsSimpleEffects <- data.frame( G = Gs, df = rep(A-1, B), Gcorrected = Gs / cf, pvalue = ps, etasq = apply( nij/ndj, 1, anofaES) ) rownames(resultsSimpleEffects) <- paste(subfact, lvls, sep=" | ") resultsSimpleEffects } emf2way <- function(w, subfacts, nestfact){ ## Herein, the factors decomposed are called factors A*B, ## that is, the effects of (A, B, A*B) within c1, the effects of (A, B, A*B) within c2, etc. ## We can get here if (a) there are 3 factors, (b) there are 4 factors. # The factor positions in the factor list and their number of levels posA <- (1:length(w$nlevels))[w$factColumns==subfacts[1]] A <- w$nlevels[posA] posB <- (1:length(w$nlevels))[w$factColumns==subfacts[2]] B <- w$nlevels[posB] # posC <- (1:length(w$factColumns))[w$factColumns==nestfact] # C <- w$nlevels[posC] if (length(nestfact)==1) { posC <- (1:length(w$nlevels))[w$factColumns==nestfact] C <- w$nlevels[posC] lvls <- w$clevels[[posC]] } else { C <-1 lvls <- c() for (i in nestfact) { pos <- (1:length(w$nlevels))[w$factColumns==i] C <- C * w$nlevels[pos] lvls <- unlist(lapply(w$clevels[[pos]], function(x) paste(x,lvls, sep=":"))) } nestfact <- paste(nestfact, collapse = "+") } # the total n and the matrix marginals nddd <- sum(w$compiledData[[w$freqColumn]]) nddk <- aggregate(as.formula(paste(w$freqColumn, nestfact, sep="~")), data = w$compiledData, sum)[[w$freqColumn]] by2 <- paste(subfacts, nestfact, sep="+") nidk <- matrix(aggregate(as.formula(paste(w$freqColumn, by2[[1]],sep="~")), data = w$compiledData, sum)[[w$freqColumn]], A,C ) ndjk <- matrix(aggregate(as.formula(paste(w$freqColumn, by2[[2]],sep="~")), data = w$compiledData, sum)[[w$freqColumn]], B,C ) # # here is ok for a three factor design only... use tt uu with %in% # nijd <- array(aggregate(as.formula(paste(w$freqColumn, paste(subfacts, collapse=" + "), sep="~")), # data = w$compiledData, sum)[[w$freqColumn]],c(A,B,C)) by3 <- paste(paste(subfacts, collapse=" + "), nestfact, sep = " + ") nijk <- array(aggregate(as.formula(paste(w$freqColumn, by3, sep="~")), data = w$compiledData, sum)[[w$freqColumn]],c(A,B,C)) # First, we compute the expected frequencies e separately for each levels of factor C eidgivenk <- nddk / A edjgivenk <- nddk / B eijgivenk <- nddk / (A * B) # Second, we get the G statistics for each level Gs <- c() for (k in 1:C) { Gs[(k-1)*3+1] <- 2 * sum(nijk[,,k] * (log(nijk[,,k])- log(eijgivenk[k]))) Gs[(k-1)*3+2] <- 2 * sum(nidk[,k] * (log(nidk[,k])- log(eidgivenk[k]))) Gs[(k-1)*3+3] <- 2 * sum(ndjk[,k] * (log(ndjk[,k])- log(edjgivenk[k]))) Gs[(k-1)*3+1] <- Gs[(k-1)*3+1] - Gs[(k-1)*3+2] - Gs[(k-1)*3+3] # remove simple effects } # Third, the correction factor (Williams, 1976) for each cfA <- 1+ (A^2-1) / ( 6 * (A-1) * nddd) cfB <- 1+ (B^2-1) / ( 6 * (B-1) * nddd) cfAB <- 1+ ((A*B)^2-1) / ( 6 * (A-1) * (B-1) * nddd) alletasq <- c() for (k in 1:C) { alletasq[(k-1)*3+1] <- anofaES(as.vector(nijk[,,k])/nddk[k]) alletasq[(k-1)*3+2] <- anofaES(nidk[,k]/nddk[k]) alletasq[(k-1)*3+3] <- anofaES(ndjk[,k]/nddk[k]) } # Finally, getting the p-values for each corrected effect ps <- 1- pchisq( Gs / c(cfAB, cfA, cfB), df = c((A-1)*(B-1), A-1, B-1) ) # This is it! let's put the results in a table resultsSimpleEffects <- data.frame( G = Gs, df = rep(c((A-1)*(B-1), A-1, B-1), C), Gcorrected = Gs / c(cfAB, cfA, cfB), pvalue = ps, etasq = alletasq ) lbl <- c(paste(subfacts, collapse=":"), subfacts ) rownames(resultsSimpleEffects) <- unlist(lapply(lvls, \(x) paste(lbl, x, sep=" | "))) resultsSimpleEffects } ########################################## # # # ██╗ ██╗███████╗██████╗ ███████╗ # # ██║ ██║██╔════╝██╔══██╗██╔════╝ # # ███████║█████╗ ██████╔╝█████╗ # # ██╔══██║██╔══╝ ██╔══██╗██╔══╝ # # ██║ ██║███████╗██║ ██║███████╗ # # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ # # # ########################################## # Coding third-order simple effects # # is postponed until interest is shown. # ########################################## emf3way <- function(w, subfacts, nestfact){ ## Herein, the factor decomposed is called factor D, ## that is, the effect of (A, B, C, AB, AC, BC, A*B*C) within d1, ## the effect of (A, B, C, AB, AC, BC, A*B*C) within d2, etc. ## There is only one way to get here: a 4 factor design is decomposed. "If you need this functionality, please contact the author...\n" }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-emFrequencies.R
################################################################################### #' @title logical functions for formulas #' #' @aliases is.formula is.one.sided has.nested.terms has.cbind.terms in.formula sub.formulas #' #' @md #' #' @description The functions `is.formula()`, `is.one.sided()`, #' `has.nested.terms()`, #' `has.cbind.terms()`, `in.formula()` and `sub.formulas()` #' performs checks or extract sub-formulas from a given formula. #' #' @usage is.formula(frm) #' @usage is.one.sided(frm) #' @usage has.nested.terms(frm) #' @usage has.cbind.terms(frm) #' @usage in.formula(frm, whatsym) #' @usage sub.formulas(frm, head) #' #' @param frm a formula; #' @param whatsym a symbol to search in the formula; #' @param head the beginning of a sub-formula to extract #' #' @return `is.formula(frm)`, `has.nested.terms(frm)`, and `has.cbind.terms(frm)` #' returns TRUE if frm is a formula, contains a '|' or a 'cbind' respectively; #' `in.formula(frm, whatsym)` returns TRUE if the symbol `whatsym` is somewhere in 'frm'; #' `sub.formulas(frm, head)` returns a list of all the sub-formulas which contains `head`. #' #' @details These formulas are for internal use. #' #' @examples #' is.formula( Frequency ~ Intensity * Pitch ) #' #' has.nested.terms( Level ~ Factor | Level ) #' #' has.cbind.terms( Frequency ~ cbind(Low,Medium,High) * cbind(Soft, Hard) ) #' #' in.formula( Frequency ~ Intensity * Pitch, "Pitch" ) #' #' sub.formulas( Frequency ~ cbind(Low,Medium,High) * cbind(Soft, Hard), "cbind" ) #' #' ################################################################################### #' #' @export is.formula #' @export is.one.sided #' @export has.nested.terms #' @export has.cbind.terms #' @export in.formula #' @export sub.formulas # ################################################################################### ################################################################################# # logical functions: ################################################################################# is.formula <- function( frm ) inherits( frm, "formula") is.one.sided <- function( frm ) is.formula(frm) && length(frm) == 2 has.nested.terms <- function( frm ) { if(!is.formula(frm)) return(FALSE) return ( in.formula(frm, "|")) } has.cbind.terms <- function( frm ) { if(!is.formula(frm)) return(FALSE) return ( in.formula(frm, "cbind")) } # performs a depth-first search in the language structure. in.formula <- function( frm, whatsym) { if ((is.symbol(frm))&&(frm == whatsym)) return(TRUE) if (!is.symbol(frm)) { for (i in (1:length(frm)) ) { if (in.formula( frm[[i]], whatsym) ) return(TRUE) } } return(FALSE) } ## Lists all the locations of head of a subformula in formula sub.formulas <- function( frm, head ) { if (!in.formula( frm, head)) stop("error! head not in frm") res <- rrapply::rrapply( frm, condition = function(x) x == head, f = function(x, .xpos) .xpos, how = "flatten" ) # grab the terms, removing last index to have the subformula lapply(res, function(i) frm[[i[1:(length(i)-1)]]]) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-logicals.R
############################################################################## # DEFINITIONS of the three display methods: # print: The usual, just show a list of three numbers, (lowerCI, dp, upperCI) # summarize (or summary): provides a human-readable output # explain : provides all sorts of information regarding the computations ############################################################################## # # As a reminder, the ANOFAobject has all these keys # type : "ANOFAomnibus" or "ANOFAsimpleeffects" # formula : the formula given to anofa # compiledData : a data.frame with the compiled frequencies # freqColumn : column in the compiled format; default "Frequency", # factColumns : c(fact mames) # nlevels : number of levels for each factors, # clevels : list of categories for each factor # marginals : marginal frequencies # results : the anofa table # ############################################################################## #' #' @title explain #' #' @name explain #' #' @md #' #' @description #' `explain()` provides a human-readable, exhaustive, description of #' the results. It also provides references to the key results. #' #' @usage explain(object, ...) #' #' @param object an object to explain #' @param ... ignored #' #' @return a human-readable output with details of computations. #' #' @export explain <- function(object, ...) { UseMethod("explain") } #' @export explain.default <- function(object, ...) { print(object) } #' @title summarize #' #' @name summarize #' #' @md #' #' @description #' `summarize()` provides a human-readable output of an ANOFAobject. it is #' synonym of `summary()` (but as actions are verbs, I used a verb). #' #' @param object an object to summarize #' @param ... ignored #' #' @return a human-readable output as per articles. #' #' @export summarize <- function(object, ...) { UseMethod("summarize") } #' @method summarize default #' @export summarize.default <- function(object, ...) { print(object$results, ...) } #' @export summary.ANOFAobject <- function(object, ...) { summarize(object, ...) } ############################################################################## ## ## Implementation of the three methods ## ############################################################################## #' @method print ANOFAobject #' @export print.ANOFAobject <- function(x, ...) { print("method print not yet done...") cat("ANOFA completed. My first advise is to use anofaPlot() now. \n") cat("Use summary() or summarize() to obtain the ANOFA table.\n") y <- unclass(x) class(y) <- "list" print(y, digits = 5) return(invisible(x)) } #' @method print ANOFAtable #' @export print.ANOFAtable <- function(x, ...) { r <- x class(r) <- "data.frame" print(round(r, getOption("ANOFA.digits")+2), digits = getOption("ANOFA.digits"), scientific = FALSE ) } #' @method summarize ANOFAobject #' @export summarize.ANOFAobject <- function(object, ...) { if (length(object$result) == 1) cat(object$result) else { u <- object$results class(u) <- c("ANOFAtable", class(u)) } return(u) } #' @method explain ANOFAobject #' @export explain.ANOFAobject <- function(object, ...) { print("method explain not yet done...") ## if one G is smaller than zero, refers to Feinberg, 1970b return(invisible(object)) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-methods.R
############################################################################## #' @details ANOFA library for analyses of frequency data #' #' @md #' #' @description `ANOFA` is a library to perform frequency data analyses. #' It is based on the G statistics (first developed by Fisher). #' This statistics is fully additive and can be decomposed in #' main effects and interaction effects, in simple effects in the #' decomposition of a significant interaction, in contrasts, etc. #' The present library performs these analyses and also can be used #' to plan statistical power for the analysis of frequency, obtain #' plots of the various effects, etc. It aims at replicating the most #' commonly-used ANOVA commands so that using this package should be #' easy. #' #' The data supplied to an ANOFA can be in three formats: (i) long format, #' (ii) wide format, (iii) compiled format, or (iv) raw format. Check #' the `anofa` commands for more precision (in what follow, we assume #' the compiled format where the frequencies are given in a column name `Freq`) #' #' The main function is #' #' \code{w <- anofa(formula, data)} #' #' where \code{formula} is a formula giving the factors, e.g., "Freq ~ A * B". #' #' For more details on the underlying math, see \insertCite{lc23b;textual}{ANOFA}. #' #' An omnibus analysis may be followed by simple effects or contrasts analyses: #' \code{emFrequencies(w, formula)} #' \code{contrast(w, listOfContrasts)} #' #' As usual, the output can be obtained with #' \code{print(w) #implicite} #' \code{summary(w) # or summarize(w) for the G statistics table} #' \code{explain(w) # for human-readable output} #' #' Data format can be converted to other format with #' \code{toLong(w)} #' \code{toWide(w)} #' \code{toCompiled(w)} #' \code{toRaw(w)} #' \code{toTabulated(w) # the only format that cannot be used as input to anofa} #' #' The package includes additional, helper, functions: \itemize{ #' \item{\code{powerXXX()}} to compute sample size given effect size; #' \item{\code{anofaPlot()}} to obtain a plot of the frequencies with error bars; #' \item{\code{effectsizeXXX()}} to compute the effect size; #' \item{\code{grf()}} to generate random frequencies from a given design. #' } #' and example datasets, some described in the article: \itemize{ #' \item{\code{LandisBarrettGalvin2013}} illustrates a 5 x 3 design; #' \item{\code{LightMargolin1971}} illustrates a 5 x 2 design; #' \item{\code{Gillet1993}} illustrates a 2 x 3 x 2 design; #' \item{\code{Detergent}} illustrates a 2 x 2 x 2 x 3 design; #' } #' #' The functions uses the following options: \itemize{ #' \item{\code{ANOFA.feedback}} ((currently unused)); #' \item{\code{ANOFA.digits}} for the number of digits displayed in G statistics tables. #' } #' #' @references #' \insertAllCited{} #' ############################################################################## #' @keywords internal "_PACKAGE" #> [1] "_PACKAGE" ############################################################################## # Create a local environment for one temporary variable... ANOFA.env <- new.env(parent = emptyenv()) .onLoad <- function(libname, pkgname) { # Set the default feedback messages displayed and the number of digits: # You can use 'all' to see all the messages, or 'none'. options( ANOFA.feedback = c('design','warnings','summary'), ANOFA.digits = 4 ) } .onDetach <- function(libpath) { # remove the options options( ANOFA.feedback = NULL, ANOFA.digits = NULL ) } ############################################################################## # to inhibit "no visible binding for global variable" errors from : # globalVariables(c("xxx","xxx","xxx")) ##############################################################################
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-package.R
###################################################################################### #' @title anofaPlot. #' #' @aliases anofaPlot count init.count CI.count #' #' @md #' #' @description The function `anofaPlot()` performs a plot of frequencies for designs #' with up to 4 factors according to the #' `ANOFA` framework. See \insertCite{lc23b;textual}{ANOFA} for more. The plot is #' realized using the `suberb` library; see \insertCite{cgh21;textual}{ANOFA}. #' The functions `count()`, `init.count()` and `CI.count()` are internal functions. #' #' @usage anofaPlot(w, formula, confidenceLevel = .95, showPlotOnly = TRUE, plotStyle = "line", #' errorbarParams = list( width =0.5, linewidth=0.75 ), ...) #' #' @usage count(n) #' @usage init.count(df) #' @usage CI.count(n, gamma =0.95) #' #' @param w An ANOFA object obtained with `anofa()`; #' #' @param formula (optional) Use formula to plot just specific terms of the omnibus test. #' For example, if your analysis stored in `w` has factors A, B and C, then #' `anofaPlot(w, ~ A * B)` will only plot the factors A and B. #' @param confidenceLevel Provide the confidence level for the confidence intervals. #' (default is 0.95, i.e., 95%). #' #' @param plotStyle (optional; default "line") How to plot the frequencies. See superb for other layouts #' (e.g., "line") #' #' @param showPlotOnly (optional, default True) shows only the plot or else shows the numbers #' needed to make the plot yourself. #' #' @param errorbarParams (optional; default list( width =0.5, linewidth=0.75 ) ) A list of #' attributes used to plot the error bars. See superb for more. #' #' @param ... Other directives sent to superb(), typically 'plotStyle', 'errorbarParams', etc. #' #' @param n the count for which a confidence interval is required #' @param df a data frame for initialization of the CI function #' @param gamma the confidence level #' #' @return a ggplot2 object of the given frequencies. #' #' #' @details The plot shows the frequencies (the count of cases) on the vertical axis as a #' function of the factors (the first on the horizontal axis, the second if any in a legend; #' and if a third or even a fourth factors are present, as distinct rows and columns). #' It also shows 95% confidence intervals of the frequency, adjusted for between-cells #' comparisons. The confidence intervals are based on the Clopper and Pearson method #' \insertCite{cp34}{ANOFA} using the Leemis and Trivedi #' analytic formula \insertCite{lt96}{ANOFA}. This "stand-alone" confidence #' interval is then adjusted for between-cell comparisons using the superb framework #' \insertCite{cgh21}{ANOFA}. #' #' See the vignette `DataFormatsForFrequencies` for more on data format and how to write their #' formula. See the vignette `ConfidenceInterval` for details on the adjustment and its purpose. #' #' @references #' \insertAllCited{} #' #' @examples #' # #' # The Landis et al. (2013) example has two factors, program of treatment and provider of services. #' LandisBarrettGalvin2013 #' #' # This examine the omnibus analysis, that is, a 5 (provider) x 3 (program): #' w <- anofa(obsfreq ~ provider * program, LandisBarrettGalvin2013) #' #' # Once processed into w, we can ask for a standard plot #' anofaPlot(w) #' #' # We place the factor `program` on the x-axis: #' anofaPlot(w, factorOrder = c("program","provider")) #' #' # The above example can also be obtained with a formula: #' anofaPlot(w, ~ program * provider) #' #' # Change the style for a plot with bars instead of lines #' anofaPlot(w, plotStyle = "bar") #' #' # Changing the error bar style #' anofaPlot(w, plotStyle = "bar", errorbarParams = list( width =0.1, linewidth=0.1 ) ) #' #' # An example with 4 factors: #' \dontrun{ #' dta <- data.frame(Detergent) #' dta #' #' w <- anofa( Freq ~ Temperature * M_User * Preference * Water_softness, dta ) #' anofaPlot(w) #' anofaPlot(w, factorOrder = c("M_User","Preference","Water_softness","Temperature")) #' #' #' # Illustrating the main effect of Temperature (not interacting with other factors) #' # and the interaction Preference * Previously used M brand #' # (Left and right panels of Figure 4 of the main article) #' anofaPlot(w, ~ Temperature) #' anofaPlot(w, ~ Preference * M_User) #' #' # All these plots are ggplot2 so they can be followed with additional directives, e.g. #' library(ggplot2) #' anofaPlot(w, ~ Temperature) + ylim(200,800) + theme_classic() #' anofaPlot(w, ~ Preference * M_User) + ylim(100,400) + theme_classic() #' } #' # etc. Any ggplot2 directive can be added to customize the plot to your liking. #' # See the vignette `Example2`. #' ###################################################################################### #' #' @export anofaPlot #' @export count #' @export init.count #' @export CI.count #' @importFrom utils capture.output #' @importFrom Rdpack reprompt # ###################################################################################### # First, we need the summary function that computes the frequency. # this is actually the datum when the data are in compiled format, so there is nothing to do. count <- function(n) n[1] # Second, we need an initalizer that will fetch the total sample size # and dump it in the global environment for later use init.count <- function(df) { # ANOFAtotalcount <<- sum(df$DV) assign('ANOFAtotalcount', sum(df$DV), ANOFA.env) } # Third, we compute the limits using Clopper & Pearson 1934 approach. # This is the Leemis and Trivedi (1996) analytic form. CI.count <- function(n, gamma=0.95) { #N <- ANOFAtotalcount N <- ANOFA.env$ANOFAtotalcount # shorter to write... # Clopper & Pearson CI from Leemis & Trivedi, 1996 plow <- (1+(N-n+1)/((n+0)*qf(1/2-gamma/2,2*(n+0),2*(N-n+1))))^(-1) phig <- (1+(N-n+0)/((n+1)*qf(1/2+gamma/2,2*(n+1),2*(N-n+0))))^(-1) # convert to CI on counts nlow <- N * plow nhig <- N * phig # multiply width by 2 for difference- and correlation-adjustments 2 * c( nlow[1]-n[1], nhig[1]-n[1] ) + n[1] } ################################################################ # This is it! let's make the plot # ################################################################ # make the plot: just a proxy for suberbPlot anofaPlot <- function(w, formula = NULL, confidenceLevel = 0.95, showPlotOnly = TRUE, plotStyle = "line", # lines by default errorbarParams = list( width =0.5, linewidth=0.75 ), # thicker error bars ... # will be transmitted to superb as is ){ ############################################################################## ## STEP 1: validating the formula if one is given ############################################################################## if (!is.null(formula)) { # 1.1 is it a legitimate formula? if (!(is.formula(formula))) stop("ANOFA::error(12): The formula argument is not a legitimate formula. Exiting...") # 1.2 If the dependent variable is named (optional), is it the correct variable if (length(formula)==3) { if (formula[[2]] != w$freqColumn) stop("ANOFA::error(13): The lhs of formula is not the correct frequency variable. Exiting...") } # if everything ok, let's compile the data bsfact <- all.vars(formula)[ ! all.vars(formula) == w$freqColumn] cdata <- aggregate(as.formula(paste(w$freqColumn, paste(bsfact,collapse="+"), sep="~")), data = w$compiledData, sum) } else { bsfact <- w$factColumns cdata <- w$compiledData } if ((confidenceLevel >= 1)||(confidenceLevel <=0.0)) stop("ANOFA::error(14): The confidence level is not within 0 and 1 (i.e., within 0% and 100%). Exiting...") ############################################################################## ## All done! ask for the plot or the data ############################################################################## # quiet superb's information opt <- getOption("superb.feedback") on.exit(options(opt)) options(superb.feedback = 'none') if (showPlotOnly) { # generate the plot res <- superb::superbPlot( cdata, BSFactors = bsfact, variables = as.character(w$freqColumn), # as it may be a symbol statistic = "count", # the summary statistics defined above errorbar = "CI", # its precision define above gamma = confidenceLevel, # the following is for the look of the plot plotStyle = plotStyle, errorbarParams = errorbarParams, ...## passed as is to superb ) + ggplot2::ylab("Freqency") } else { # only compute the summary statistics res <- superb::superbData( cdata, BSFactors = bsfact, variables = as.character(w$freqColumn), # as it may be a symbol statistic = "count", # the summary statistics defined above errorbar = "CI", # its precision define above gamma = confidenceLevel )$summaryStatistics } # restore superb's information: done with on.exit() # options(superb.feedback = opt) return(res) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-plot.R
#################################################################################### #' @title Computing power within the ANOFA. #' #' @aliases anofaPower2N anofaN2Power #' #' @md #' #' @description The function `anofaN2Power()` performs an analysis of statistical power #' according to the `ANOFA` framework. See \insertCite{lc23b;textual}{ANOFA} for more. #' `anofaPower2N()` computes the sample size to reach a given power. #' #' @usage anofaPower2N(power, P, f2, alpha) #' #' @usage anofaN2Power(N, P, f2, alpha) #' #' @param power target power to attain; #' #' @param N sample size; #' #' @param P number of groups; #' #' @param f2 effect size Cohen's $f^2$; #' #' @param alpha (default if omitted .05) the decision threshold. #' #' #' @return a model fit to the given frequencies. The model must always be an omnibus model #' (for decomposition of the main model, follow the analysis with `emfrequencies()` or `contrasts()`) #' #' #' #' @references #' \insertAllCited{} #' #' @examples #' # 1- The Landis et al. study had tremendous power with 533 participants in 15 cells: #' # where 0.2671 is the observed effect size for the interaction. #' anofaN2Power(533, 5*3, 0.2671) #' # power is 100% because sample is large and effect size is as well. #' #' # Even with a quarter of the participants, power is overwhelming: #' # because the effect size is quite large. #' anofaN2Power(533/4, 5*3, 0.2671) #' #' # 2- Power planning. #' # Suppose we plan a four-classification design with expected frequencies of: #' pred <- c(.35, .25, .25, .15) #' # P is the number of classes (here 4) #' P <- length(pred) #' # We compute the predicted f2 as per Eq. 5 #' f2 <- 2 * sum(pred * log(P * pred) ) #' # the result, 0.0822, is a moderate effect size. #' #' # Finally, aiming for a power of 80%, we run #' anofaPower2N(0.80, P, f2) #' # to find that a little more than 132 participants are enough. #' #################################################################################### #' #' @importFrom stats optimize #' @export anofaN2Power #' @export anofaPower2N #' @importFrom utils capture.output # #################################################################################### # 1- Returns statistical power given N, P, f2 and alpha anofaN2Power <- function(N, P, f2, alpha = .05) { pFc <- qchisq( p = 1 - alpha, df = P-1 ) 1- pchisq(q = pFc, df = P-1, ncp = N * f2) } # 2- Performs a search for N to reach a certain statistical power library(stats) # for function optimize anofaPower2N <- function(power, P, f2, alpha = .05) { # define the objective: minimize the lag between the desired power and # the power achieved by a certain N objective <- function(N, power, P, f2, alpha = .05) { (power - anofaN2Power(N, P, f2, alpha))^2 } # launch optimization search for the desired N between 10 and 1000 optimize( objective, interval = c(10,1000), P = P, f2 = f2, power = power)$minimum }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-power.R
###################################################################################### #' @title Generating random frequencies #' #' @md #' #' @description The function `GRF()` #' generates random frequencies based on a design, i.e., #' a list giving the factors and the categories with each factor. #' The data are given in the `compiled` format. #' #' @usage GRF( design, n, prob = NULL, f = "Freq" ) #' #' @param design A list with the factors and the categories within each. #' @param n How many simulated participants are to be classified. #' @param prob (optional) the probability of falling in each cell of the design. #' @param f (optional) the column names that will contain the frequencies. #' #' @return a data frame containing frequencies per cells of the design. #' #' @details The name of the function `GRF()` is derived from `grd()`, #' a general-purpose tool to generate random data \insertCite{ch19}{ANOFA} now bundled #' in the `superb` package \insertCite{cgh21}{ANOFA}. #' #' @references #' \insertAllCited{} #' #' @examples #' #' # The first example disperse 20 particants in one factor having #' # two categories (low and high): #' design <- list( A=c("low","high")) #' GRF( design, 20 ) #' #' # This example has two factors, with factor A having levels a, b, c: #' design <- list( A=letters[1:3], B = c("low","high")) #' GRF( design, 40 ) #' #' # This last one has three factors, for a total of 3 x 2 x 2 = 12 cells #' design <- list( A=letters[1:3], B = c("low","high"), C = c("cat","dog")) #' GRF( design, 100 ) #' #' # To specify unequal probabilities, use #' design <- list( A=letters[1:3], B = c("low","high")) #' GRF( design, 100, c(.05, .05, .35, .35, .10, .10 ) ) #' #' # The name of the column containing the frequencies can be changes #' GRF( design, 100, f="patate") #' ###################################################################################### #' @importFrom stats rmultinom #' @export GRF # ###################################################################################### # generate compiled-format data from a list of the factors and their levels GRF <- function( design, n, prob = NULL, f = "Freq" ) { levels <- sapply(design, length, simplify = TRUE) nlevels <- prod(levels) if (is.null(prob)) { prob <- rep(1/nlevels, nlevels) } else { if (length(prob) != nlevels) stop("ANOFA::error(51): number of probabilities provided does not match the number of cells. Exiting...") if (round(sum(prob),3) !=1.0) stop("ANOFA::error(52): The total of the probabilities does not equal 1. Exiting...") } res <- expand.grid(design) res[[f]] = rmultinom(1, n, prob)[,1] return(res) }
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/ANOFA-random.R
#' Detergent data #' #' The data, taken from \insertCite{rs63;textual}{ANOFA}, is a dataset examining #' the distribution of a large sample of customers, classified over #' four factors: #' `Softness of water used` (3 levels: soft, medium or hard), #' `Expressed preference for brand M or X after blind test` (2 levels: #' Brand M or Brand X), `Previously used brand M` (2 levels: yes #' or no), and `Temperature of landry water` (2 levels: hot or #' cold). It is therefore a 3 × 2 × 2 × 2 design with 24 cells. #' #' @md #' #' @docType data #' #' @usage Detergent #' #' @format An object of class list. #' #' @keywords datasets #' #' @references #' \insertAllCited{} #' #' @source \doi{10.20982/tqmp.19.2.p173} #' #' @examples #' #' # convert the data to a data.frame #' dta <- data.frame(Detergent) #' #' # run the anofa analysis #' \dontrun{ #' w <- anofa( Freq ~ Temperature * M_User * Preference * Water_softness, dta) #' #' # make a plot with all the factors #' anofaPlot(w) #' #' # ... or with just a few factors #' anofaPlot(w, ~ Preference * M_User ) #' anofaPlot(w, ~ Temperature ) #' #' # extract simple effects #' e <- emFrequencies(w, ~ M_User | Preference ) #' } #' "Detergent"
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/Detergent.R
###################################################################################### #' #' @title Gillet1993 #' #' @description The data, taken from \insertCite{g93;textual}{ANOFA}, is a dataset examining #' the distribution of apple tree to produce new branches from grafts. The study has #' a sample of 713 trees subdivided into three factors: #' `species` (2 levels: Jonagold or Cox); #' `location` (3 levels: Order1, Order2, Order3); #' is where the graft has been implanted (order 1 is right on the trunk); #' and `florished` (2 levels: yes or no) indicates if the branch bear #' flowers. It is therefore a 2 × 3 × 2 design with 12 cells. #' #' @md #' #' @docType data #' #' @usage Gillet1993 #' #' @format An object of class list. #' #' @keywords datasets #' #' @references #' \insertAllCited{} #' #' @examples #' # The Gillet1993 presents data from appletrees having grafts. #' Gillet1993 #' #' # run the base analysis #' w <- anofa( Freq ~ species * location * florished, Gillet1993) #' #' # display a plot of the results #' anofaPlot(w) #' #' # show the anofa table where we see the 3-way interaction #' summary(w) #' #' # This returns the expected marginal frequencies analysis #' e <- emFrequencies(w, Freq ~ species * location | florished ) #' summary(e) #' #' # as seen, all the two-way interactions are significant. Decompose one more degree: #' f <- emFrequencies(w, Freq ~ species | florished * location ) #' summary(f) #' #' "Gillet1993"
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/Gillet1993.R
#' LandisBarrettGalvin2013 data #' #' The data, taken from \insertCite{lbg13;textual}{ANOFA}, is a dataset where the #' participants (n = 553) are classified according to two factors, #' first, how modalities of care in a family #' medicine residency program were given. The possible cases were `Collocated #' Behavioral Health service` (CBH), a `Primary-Care #' Behavioral Health service` (PBH) and a `Blended Model` (BM). #' Second, how a patient’s care was financed: #' `Medicare` (MC), `Medicaid` (MA), a `mix of Medicare/Medicaid` #' (MC/MA), `Personal insurance` (PI), or `Self-paid` ($P). This #' design therefore has 5 x 3 = 15 cells. It was thoroughly examined #' in \insertCite{s15}{ANOFA} and analyzed in \insertCite{lc23b}{ANOFA}. #' #' @md #' #' @docType data #' #' @usage LandisBarrettGalvin2013 #' #' @format An object of class data.frame. #' #' @keywords datasets #' #' @references #' \insertAllCited{} #' #' @source \doi{10.1037/a0033410} #' #' @examples #' #' # running the anofa #' L <- anofa( obsfreq ~ provider * program, LandisBarrettGalvin2013) #' #' # getting a plot #' anofaPlot(L) #' #' # the G table shows a significant interaction #' summary(L) #' #' # getting the simple effect #' e <- emFrequencies(L, ~ program | provider ) #' #' ## Getting some contrast by provider (i.e., on e) #' f <- contrastFrequencies(e, list( #' "(PBH & CBH) vs. BM"=c(1,1,-2)/2, #' "PBH vs. CBH"=c(1,-1,0)) #' ) #' #' "LandisBarrettGalvin2013"
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/LandisBarrettGalvin2013.R
#' LightMargolin1971 data #' #' The data, taken from \insertCite{lm71;textual}{ANOFA}, is an example where the #' educational aspiration of a large sample of N = #' 617 adolescents. The participants are classified by their #' gender (2 levels) and by their educational aspiration ( #' complete secondary school, complete vocational training, #' become college teacher, complete gymnasium, or complete #' university; 5 levels). #' #' @md #' #' @docType data #' #' @usage LightMargolin1971 #' #' @format An object of class data.frame. #' #' @keywords datasets #' #' @references #' \insertAllCited{} #' #' @source \doi{10.1080/01621459.1971.10482297} #' #' @examples #' library(ANOFA) #' #' options(superb.feedback = 'none') # shut down 'warnings' and 'design' interpretation messages #' #' # Lets run the analysis #' L <- anofa( obsfreq ~ vocation * gender, LightMargolin1971) #' summary(L) #' #' # a quick plot #' anofaPlot(L) #' #' # Some simple effects. #' e <- emFrequencies(L, ~ gender | vocation ) #' summary(e) #' #' # some contrasts: #' e <- emFrequencies(L, ~ vocation | gender ) #' f <- contrastFrequencies(e, list( #' "teacher college vs. gymnasium"=c( 0, 0, 1,-1, 0), #' "vocational vs. university" = c( 0, 1, 0, 0,-1), #' "another" = c( 0, 1,-1,-1,+1)/2, #' "to exhaust the df" = c( 4,-1,-1,-1,-1)/4 #' ) #' ) #' #' "LightMargolin1971"
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/LightMargolin1971.R
################################################################################### #' @title minimalExample #' #' @name minimalExample #' #' @description The data in compiled format are analyzed with an #' Analysis of Frequency Data method (described in \insertCite{lc23b}{ANOFA}. #' #' @md #' #' @docType data #' #' @format An object of class data.frame. #' #' @keywords datasets #' #' @references #' \insertAllCited{} #' #' @source \doi{10.20982/tqmp.19.2.p173} #' #' @examples #' library(ANOFA) #' #' # the minimalExample data (it has absolutely no effect...) #' minimalExample #' #' # perform an anofa on this dataset #' w <- anofa( Frequency ~ Intensity * Pitch, minimalExample) #' #' # We analyse the intensity by levels of pitch #' e <- emFrequencies(w, ~ Intensity | Pitch) #' #' # decompose by #' f <- contrastFrequencies(e, list( #' "low & medium compared to high" = c(1,1,-2)/2, #' "low compared to medium " = c(1,-1,0))) #' #' "minimalExample"
/scratch/gouwar.j/cran-all/cranData/ANOFA/R/minimalExample.R
## ---- echo = FALSE, message = FALSE, results = 'hide', warning = FALSE-------- cat("this will be hidden; use for general initializations.\n") library(ANOFA) ## ---- message=FALSE, warning=FALSE, fig.width=5, fig.height=3, fig.cap="**Figure 1**. The frequencies of the Light & Margolin, 1971, data as a function of aspiration for higher education and as a function of gender. Error bars show difference-adjusted 95% confidence intervals."---- library(ANOFA) w <- anofa( obsfreq ~ vocation * gender, LightMargolin1971) anofaPlot(w) ## ---- message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 2**. The frequencies of the Light & Margolin, 1971, data as a function of gender. Error bars show difference-adjusted 95% confidence intervals."---- anofaPlot(w, obsfreq ~ gender) ## ---- message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 3**. Same as Figure 2 with some customization."---- library(ggplot2) anofaPlot(w, obsfreq ~ gender) + theme_bw()
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/ConfidenceIntervals.R
--- title: "Confidence intervals with frequencies" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes how to plot confidence intervals with frequencies. vignette: > %\VignetteIndexEntry{Confidence intervals with frequencies} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this will be hidden; use for general initializations.\n") library(ANOFA) ``` Probably the most useful tools for data analysis is a plot with suitable error bars [@cgh21]. In this vignette, we show how to make confidence intervals for frequencies ## Theory behind Confidence intervals for Frequencies For frequencies, ANOFA does not lend itself to confidence intervals. Hence, we decided to use @cp34 pivot technique. This technique returns _stand-alone_ confidence intervals on a proportion, that is, an interval which can be used to compare an observed proportion to a theoretical value. In order to compare an observed proportion to another proportion, it is necessary to adjust the wide [see @cgh21]. Further, because we want an interval for frequencies, we multiply the proportion by the total number of data $N$. Herein, we use the @lt96 method which provides an analytical solution based on the Fisher's $F$ distribution. It is based on $n$, the observed frequency in a given cell, $N$, the total number of observations, and $1-\alpha$, the confidence level (typically 95%). It is given by $$\hat{\pi}_{\text{low}}=\left( 1+\frac{N-n+1}{n F_{1-\alpha/2}(2n,2(N-n+1)} \right)^{-1} < {\pi} < \left( 1+\frac{N-n}{(n+1) F_{\alpha/2}(2(n+1),2(N-x)}\right)^{-1} =\hat{\pi}_{\text{high}}$$ This interval wide is then multiply by $N$ with $\{n_{\text{low}}, n_{\text{high}} \} = N \, \times\, \{ \hat{\pi}_{\text{low}}, \hat{\pi}_{\text{high}} \}$ so that we obtain an interval on frequencies rather than on probabilities. Finally, the width of the intervals are adjusted for difference and correlations using: $$n_{\text{low}}^* = \sqrt{2} \sqrt{2}(n-n_{\text{low}})+n$$ $$n_{\text{high}}^* = \sqrt{2} \sqrt{2}(n_{\text{high}}-n)+n$$ The lower and upper length are adjusted separately because this interval may not be symmetrical (equal length) on both side of the observed frequency $n$. This is it. ## Complicated? Well, not really: ```{r, message=FALSE, warning=FALSE, fig.width=5, fig.height=3, fig.cap="**Figure 1**. The frequencies of the Light & Margolin, 1971, data as a function of aspiration for higher education and as a function of gender. Error bars show difference-adjusted 95% confidence intervals."} library(ANOFA) w <- anofa( obsfreq ~ vocation * gender, LightMargolin1971) anofaPlot(w) ``` You can select only some factors for plotting, with e.g., ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 2**. The frequencies of the Light & Margolin, 1971, data as a function of gender. Error bars show difference-adjusted 95% confidence intervals."} anofaPlot(w, obsfreq ~ gender) ``` Because of the interaction _gender_ $\times$ _vocational aspiration_, the overall difference between boys and girls is small. Actually, they differ only in their aspiration to go to the university (recall that these are 1960s data...). As is the case with any ``ggplot2`` figure, you can customize it at will. For example, ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 3**. Same as Figure 2 with some customization."} library(ggplot2) anofaPlot(w, obsfreq ~ gender) + theme_bw() ``` Here you go. # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/ConfidenceIntervals.Rmd
## ---- echo = FALSE, message = FALSE, results = 'hide', warning = FALSE-------- cat("this is hidden; general initializations.\n") library(ANOFA) w<-anofa(Frequency ~ Intensity * Pitch, minimalExample) dataRaw <- toRaw(w) dataWide <- toWide(w) dataCompiled <-toCompiled(w) dataLong <- toLong(w) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- library(ANOFA) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- dataRaw ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- dataWide ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa( ~ Intensity * Pitch, dataWide) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- dataCompiled ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa(Frequency ~ Intensity * Pitch, dataCompiled ) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- dataLong ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa( Level ~ Factor | Id, dataLong) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- toCompiled(w) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) toCompiled(w) ## ---- message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE---------------------- w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw, factors = c("Intensity","Pitch") ) toCompiled(w)
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/DataFormatsForFrequencies.R
--- title: "Data formats for frequencies" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes the various ways that frequencies can be entered in a data.frame. vignette: > %\VignetteIndexEntry{Data formats for frequencies} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this is hidden; general initializations.\n") library(ANOFA) w<-anofa(Frequency ~ Intensity * Pitch, minimalExample) dataRaw <- toRaw(w) dataWide <- toWide(w) dataCompiled <-toCompiled(w) dataLong <- toLong(w) ``` # Data formats for frequencies Frequencies are actually not raw data: they are the counts of data belonging to a certain cell of your design. As such, they are _summary statistics_, a bit like the mean is a summary statistic of data. In this vignette, we review various ways that data can be coded in a data frame. All along, we use a simple example, (ficticious) data of speakers classified according to their ability to play high intensity sound (low ability, medium ability, or high ability, three levels) and the pitch with which they play these sound (soft or hard, two levels). This is therefore a design with two factors, noted in brief a $3 \times 2$ design. A total of 20 speakers have been examined ($N=20$). Before we begin, we load the package ``ANOFA`` (if is not present on your computer, first upload it to your computer from CRAN or from the source repository ``devtools::install_github("dcousin3/ANOFA")``): ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} library(ANOFA) ``` ## First format: Raw data format In this format, there is one line per _subject_ and one column for each possible category (one for low, one for medium, etc.). The column contains a 1 (a checkmark if you wish) if the subject is classified in this category and zero for the alternative categories. In a $3 \times 2$ design, there is therefore a total of $3+2 = 5$ columns. The raw data are: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataRaw ``` To provide raw data to ``anofa()``, the formula must be given as ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) ``` where ``cbind()`` is used to group the categories of a single factor. The formula has no left-hand side (lhs) term because the categories are signaled by the columns named on the left. This format is actually the closest to how the data are recorded: if you are coding the data manually, you would have a score sheed and placing checkmarks were appropriate. ## Second format: Wide data format In this format, instead of coding checkmarks under the relevant category (using 1s), only the applicable category is recorded. Hence, if ability to play high intensity is 1 (and the others zero), this format only keep "High" in the record. Consequently, for a design with two factors, there is only two columns, and as many lines as there are subjects: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataWide ``` To use this format in ``anofa``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ Intensity * Pitch, dataWide) ``` (you can verify that the results are identical, whatever the format by checking ``summary(w)``). ## Third format: dataCompiled This format is compiled, in the sense that the frequencies have been count for each cell of the design. Hence, we no longer have access to the raw data. In this format, there is $3*2 = 6$ lines, one for each combination of the factor levels, and $2+1 = 3$ columns, two for the factor levels and 1 for the count in that cell (aka the frequency). Thus, ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataCompiled ``` To use a compiled format in ``anofa``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa(Frequency ~ Intensity * Pitch, dataCompiled ) ``` where ``Frequency`` identifies in which column the counts are stored. ## Fourth format: dataLong This format may be prefered for linear modelers (but it may rapidly becomes _very_ long!). There is always the same three columns: One Id column, one column to indicate a factor, and one column to indicate the observed level of that factor for that subject. There are $20 \times 2 =40 $ lines in the present example (number of subjects times number of factors.) ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataLong ``` To analyse such data format within ``anofa()``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( Level ~ Factor | Id, dataLong) ``` The vertical line symbol indicates that the observations are nested within ``Id`` (i.e., all the lines with the same Id are actually the same subject). ## Converting between formats Once entered in an ``anofa()`` structure, it is possible to convert to any format using ``toRaw()``, ``toWide()``, ``toCompiled()`` and ``toLong()``. For example: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} toCompiled(w) ``` The compiled format is probably the most compact format, but the raw format is the most explicite format (as we see all the subjects and all the _checkmarks_ for each). The only limitation is with regards to the raw format: It is not possible to guess the name of the factors from the names of the columns. By default, ``anofa()`` will use uppercase letters to identify the factors. ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) toCompiled(w) ``` To overcome this limit, you can manually provide factor names with ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw, factors = c("Intensity","Pitch") ) toCompiled(w) ``` To know more about analyzing frequency data with ANOFA, refer to @lc23b or to [What is an ANOFA?](https://dcousin3.github.io/ANOFA/articles/WhatIsANOFA.html). # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/DataFormatsForFrequencies.Rmd
## ---- echo = FALSE, message = FALSE, results = 'hide', warning = FALSE-------- cat("this will be hidden; use for general initializations.\n") library(ANOFA) library(ggplot2) library(superb) # generate some random data with no meaning set.seed(43) #probs #alone #ingroup #harass #shout pr <- c(0.4/12,1.4/12,0.5/12, 2.3/12,1.0/12,0.5/12, 0.5/12,2.0/12,0.4/12, 0.5/12,2.0/12,0.5/12) dta <- GRF( list(Gender = c("boy", "girl", "other"), TypeOfInterplay = c("alone", "ingroup", "harrass", "shout") ), 300, pr ) ## ---- message = FALSE, warning = FALSE---------------------------------------- dta ## ---- warning = FALSE--------------------------------------------------------- library(ANOFA) w <- anofa(Freq ~ Gender * TypeOfInterplay, data = dta) ## ---- message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 1**. The frequencies of the ficticious data as a function of Gender and Type of Interplay. Error bars show difference-adjusted 95% confidence intervals."---- anofaPlot(w) ## ----------------------------------------------------------------------------- summary(w) ## ----------------------------------------------------------------------------- e <- emFrequencies(w, Freq ~ TypeOfInterplay | Gender) summary(e) ## ----------------------------------------------------------------------------- f <- contrastFrequencies(e, list( "alone vs. harass " = c(-1, 0, +1, 0 ), "(alone & harass) vs. shout " = c(-1/2, 0, -1/2, +1 ), "(alone & harass & shout) vs. in-group" = c(-1/3, +1, -1/3, -1/3) )) summary(f) ## ---- results="hold"---------------------------------------------------------- sum(summary(f)[,1]) # Gs sum(summary(f)[,2]) # degrees of freedom ## ---- results="hold"---------------------------------------------------------- sum(summary(e)[,1]) # Gs sum(summary(e)[,2]) # degrees of freedom ## ---- results="hold"---------------------------------------------------------- sum(summary(w)[c(3,4),1]) # Gs sum(summary(w)[c(3,4),2]) # degrees of freedom
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/WhatIsANOFA.R
--- title: "What is Analysis of Frequency Data?" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes what an analysis of frequency data is. vignette: > %\VignetteIndexEntry{What is Analysis of Frequency Data?} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- The _ANalysis Of Frequency datA_ (ANOFA) is a framework for analyzing frequencies (a.k.a. counts) of classification data. This framework is very similar to the well-known ANOVA and uses the same general approach. It allows analyzing _main effects_ and _interaction effects_It also allow analyzing _simple effects_ (in case of interactions) as well as _orthogonal contrats_. Further, ANOFA makes it easy to generate frequency plots which includes confidence intervals, and to compute _eta-square_ as a measure of effect size. Finally, power planning is easy within ANOFA. ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this will be hidden; use for general initializations.\n") library(ANOFA) library(ggplot2) library(superb) # generate some random data with no meaning set.seed(43) #probs #alone #ingroup #harass #shout pr <- c(0.4/12,1.4/12,0.5/12, 2.3/12,1.0/12,0.5/12, 0.5/12,2.0/12,0.4/12, 0.5/12,2.0/12,0.5/12) dta <- GRF( list(Gender = c("boy", "girl", "other"), TypeOfInterplay = c("alone", "ingroup", "harrass", "shout") ), 300, pr ) ``` ## A basic example As an example, suppose that you observe a class of primary school students, trying to ascertain the different sorts of behaviors. You might use an obsrevation grid where, for every kid observed, you check various things, such as | Student Id: A | | |:----------------|-------------------------| |**Gender:** | Boy [**x**] Girl [ ] Other [ ] | |**Type of interplay:** | Play alone [**x**] Play in group [ ] Harrass others [ ] Shout against other [ ] | |**etc.** | This grid categorizes the participants according to two factors, `Gender`, and `TypeOfInterplay`. From these observations, one may wish to know if gender is more related to one type of interplay. Alternatively, genders could be evenly spread across types of interplay. In the second case, there is no _interaction_ between the factors. ## Some data Once collected through observations, the data can be formated in one of many ways (see the vignette [Data formats](https://dcousin3.github.io/ANOFA/articles/DataFormatsForFrequencies.html)). The raw format could look like | Id | boy | girl | other | alone | in-group | harass | shout | |----|------|-------|-------|-------|----------|--------|-------| | A | 1 | 0 | 0 | 1 | 0 | 0 | 0 | | B | 0 | 0 | 1 | 0 | 0 | 1 | 0 | | C | 0 | 1 | 0 | 0 | 0 | 0 | 1 | | D | 1 | 0 | 0 | 0 | 1 | 0 | 0 | | ...| | | | | | | | For a more compact representation, the data could be _compiled_ into a table with all the combination of gender $\times$ types of interplay, hence resulting in 12 cells. The results (totally ficticious) looks like (assuming that they are stored in a data.frame named ``dta``): ```{r, message = FALSE, warning = FALSE} dta ``` for a grand total of `r sum(dta$Freq)` childs observed. ## Analyzing the data The frequencies can be analyzed using the _Analysis of Frequency Data_ (ANOFA) framework [@lc23b]. This framework only assumes that the population is _multinomial_ (which means that the population has certain probabilities for each cell). The relevant test statistic is a $G$ statistic, whose significance is assessed using a chi-square table. *ANOFA* works pretty much the same as an *ANOFA* except that instead of looking at the means in each cell, its examines the count of observations in each cell. To run an analysis of the data frame ``dta``, simply use: ```{r, warning = FALSE} library(ANOFA) w <- anofa(Freq ~ Gender * TypeOfInterplay, data = dta) ``` This is it. The formula indicates that the counts are stored in column ``Freq`` and that the factors are ``Gender`` and ``TypeOfInterplay``, each stored in its own column. (if your data are organized differently, see [Data formats](https://dcousin3.github.io/ANOFA/articles/DataFormatsForFrequencies.html)). At this point, you might want a plot showing the counts on the vertical axis: ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 1**. The frequencies of the ficticious data as a function of Gender and Type of Interplay. Error bars show difference-adjusted 95% confidence intervals."} anofaPlot(w) ``` We can note a strong interaction, the `ingroup` activity not being distributed the same as a function of ``Gender``. To confirm the interaction, let's look at the ANOFA table: ```{r} summary(w) ``` Indeed, the interaction (last line) is significant ($G(6) = 65.92$, $p < .001$). The $G$ statistics is corrected for small sample but the correction is typically small (as seen in the fourth column). We might want to examine whether the frequencies of interplay are equivalent separately for each ``Gender``, even though examination of the plot suggest that it is only the case for the ``other`` gender. This is achieved with an analysis of the _simple effects_ of `TypeOfInterplay` within each level of `Gender`: ```{r} e <- emFrequencies(w, Freq ~ TypeOfInterplay | Gender) summary(e) ``` As seen, for boys and girls, the type of interplay differ significantly (both $p < .002$); for ``others``, as expected from the plot, this is not the case ($G(3) = 1.57$, $p = 0.46$). If really, you need to confirm that the major difference is caused by the ``ingroup`` type of activity (in these ficticious data), you could follow-up with a contrast analysis. We might compare `alone` to `harass`, both to `shout`, and finally the three of them to `ingroup`. ```{r} f <- contrastFrequencies(e, list( "alone vs. harass " = c(-1, 0, +1, 0 ), "(alone & harass) vs. shout " = c(-1/2, 0, -1/2, +1 ), "(alone & harass & shout) vs. in-group" = c(-1/3, +1, -1/3, -1/3) )) summary(f) ``` Because the contrast analysis is based on the simple effects within ``Gender`` (variable ``e``), we get three contrasts for each gender. As seen, for boys, `in-group` is the sole condition triggering the difference. Same for girls. Finally, there are no difference for the last group. ## Additivity of the decomposition (optional) The main advandage of ANOFA is that all the decomposition are entirely additive. If, for example, you sum the $G$s and degrees of freedom of the contrasts, with e.g., ```{r, results="hold"} sum(summary(f)[,1]) # Gs sum(summary(f)[,2]) # degrees of freedom ``` you get exacly the same as the simple effects: ```{r, results="hold"} sum(summary(e)[,1]) # Gs sum(summary(e)[,2]) # degrees of freedom ``` which is also the same as the main analysis done first, adding the main effect of ``TypeOfInterplay`` and its interaction with ``Gender`` (lines 3 and 4): ```{r, results="hold"} sum(summary(w)[c(3,4),1]) # Gs sum(summary(w)[c(3,4),2]) # degrees of freedom ``` In other words, **the decompositions preserved all the information available**. This is the defining characteristic of ANOFA. # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/inst/doc/WhatIsANOFA.Rmd
--- title: "Confidence intervals with frequencies" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes how to plot confidence intervals with frequencies. vignette: > %\VignetteIndexEntry{Confidence intervals with frequencies} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this will be hidden; use for general initializations.\n") library(ANOFA) ``` Probably the most useful tools for data analysis is a plot with suitable error bars [@cgh21]. In this vignette, we show how to make confidence intervals for frequencies ## Theory behind Confidence intervals for Frequencies For frequencies, ANOFA does not lend itself to confidence intervals. Hence, we decided to use @cp34 pivot technique. This technique returns _stand-alone_ confidence intervals on a proportion, that is, an interval which can be used to compare an observed proportion to a theoretical value. In order to compare an observed proportion to another proportion, it is necessary to adjust the wide [see @cgh21]. Further, because we want an interval for frequencies, we multiply the proportion by the total number of data $N$. Herein, we use the @lt96 method which provides an analytical solution based on the Fisher's $F$ distribution. It is based on $n$, the observed frequency in a given cell, $N$, the total number of observations, and $1-\alpha$, the confidence level (typically 95%). It is given by $$\hat{\pi}_{\text{low}}=\left( 1+\frac{N-n+1}{n F_{1-\alpha/2}(2n,2(N-n+1)} \right)^{-1} < {\pi} < \left( 1+\frac{N-n}{(n+1) F_{\alpha/2}(2(n+1),2(N-x)}\right)^{-1} =\hat{\pi}_{\text{high}}$$ This interval wide is then multiply by $N$ with $\{n_{\text{low}}, n_{\text{high}} \} = N \, \times\, \{ \hat{\pi}_{\text{low}}, \hat{\pi}_{\text{high}} \}$ so that we obtain an interval on frequencies rather than on probabilities. Finally, the width of the intervals are adjusted for difference and correlations using: $$n_{\text{low}}^* = \sqrt{2} \sqrt{2}(n-n_{\text{low}})+n$$ $$n_{\text{high}}^* = \sqrt{2} \sqrt{2}(n_{\text{high}}-n)+n$$ The lower and upper length are adjusted separately because this interval may not be symmetrical (equal length) on both side of the observed frequency $n$. This is it. ## Complicated? Well, not really: ```{r, message=FALSE, warning=FALSE, fig.width=5, fig.height=3, fig.cap="**Figure 1**. The frequencies of the Light & Margolin, 1971, data as a function of aspiration for higher education and as a function of gender. Error bars show difference-adjusted 95% confidence intervals."} library(ANOFA) w <- anofa( obsfreq ~ vocation * gender, LightMargolin1971) anofaPlot(w) ``` You can select only some factors for plotting, with e.g., ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 2**. The frequencies of the Light & Margolin, 1971, data as a function of gender. Error bars show difference-adjusted 95% confidence intervals."} anofaPlot(w, obsfreq ~ gender) ``` Because of the interaction _gender_ $\times$ _vocational aspiration_, the overall difference between boys and girls is small. Actually, they differ only in their aspiration to go to the university (recall that these are 1960s data...). As is the case with any ``ggplot2`` figure, you can customize it at will. For example, ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 3**. Same as Figure 2 with some customization."} library(ggplot2) anofaPlot(w, obsfreq ~ gender) + theme_bw() ``` Here you go. # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/vignettes/ConfidenceIntervals.Rmd
--- title: "Data formats for frequencies" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes the various ways that frequencies can be entered in a data.frame. vignette: > %\VignetteIndexEntry{Data formats for frequencies} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this is hidden; general initializations.\n") library(ANOFA) w<-anofa(Frequency ~ Intensity * Pitch, minimalExample) dataRaw <- toRaw(w) dataWide <- toWide(w) dataCompiled <-toCompiled(w) dataLong <- toLong(w) ``` # Data formats for frequencies Frequencies are actually not raw data: they are the counts of data belonging to a certain cell of your design. As such, they are _summary statistics_, a bit like the mean is a summary statistic of data. In this vignette, we review various ways that data can be coded in a data frame. All along, we use a simple example, (ficticious) data of speakers classified according to their ability to play high intensity sound (low ability, medium ability, or high ability, three levels) and the pitch with which they play these sound (soft or hard, two levels). This is therefore a design with two factors, noted in brief a $3 \times 2$ design. A total of 20 speakers have been examined ($N=20$). Before we begin, we load the package ``ANOFA`` (if is not present on your computer, first upload it to your computer from CRAN or from the source repository ``devtools::install_github("dcousin3/ANOFA")``): ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} library(ANOFA) ``` ## First format: Raw data format In this format, there is one line per _subject_ and one column for each possible category (one for low, one for medium, etc.). The column contains a 1 (a checkmark if you wish) if the subject is classified in this category and zero for the alternative categories. In a $3 \times 2$ design, there is therefore a total of $3+2 = 5$ columns. The raw data are: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataRaw ``` To provide raw data to ``anofa()``, the formula must be given as ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) ``` where ``cbind()`` is used to group the categories of a single factor. The formula has no left-hand side (lhs) term because the categories are signaled by the columns named on the left. This format is actually the closest to how the data are recorded: if you are coding the data manually, you would have a score sheed and placing checkmarks were appropriate. ## Second format: Wide data format In this format, instead of coding checkmarks under the relevant category (using 1s), only the applicable category is recorded. Hence, if ability to play high intensity is 1 (and the others zero), this format only keep "High" in the record. Consequently, for a design with two factors, there is only two columns, and as many lines as there are subjects: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataWide ``` To use this format in ``anofa``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ Intensity * Pitch, dataWide) ``` (you can verify that the results are identical, whatever the format by checking ``summary(w)``). ## Third format: dataCompiled This format is compiled, in the sense that the frequencies have been count for each cell of the design. Hence, we no longer have access to the raw data. In this format, there is $3*2 = 6$ lines, one for each combination of the factor levels, and $2+1 = 3$ columns, two for the factor levels and 1 for the count in that cell (aka the frequency). Thus, ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataCompiled ``` To use a compiled format in ``anofa``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa(Frequency ~ Intensity * Pitch, dataCompiled ) ``` where ``Frequency`` identifies in which column the counts are stored. ## Fourth format: dataLong This format may be prefered for linear modelers (but it may rapidly becomes _very_ long!). There is always the same three columns: One Id column, one column to indicate a factor, and one column to indicate the observed level of that factor for that subject. There are $20 \times 2 =40 $ lines in the present example (number of subjects times number of factors.) ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} dataLong ``` To analyse such data format within ``anofa()``, use ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( Level ~ Factor | Id, dataLong) ``` The vertical line symbol indicates that the observations are nested within ``Id`` (i.e., all the lines with the same Id are actually the same subject). ## Converting between formats Once entered in an ``anofa()`` structure, it is possible to convert to any format using ``toRaw()``, ``toWide()``, ``toCompiled()`` and ``toLong()``. For example: ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} toCompiled(w) ``` The compiled format is probably the most compact format, but the raw format is the most explicite format (as we see all the subjects and all the _checkmarks_ for each). The only limitation is with regards to the raw format: It is not possible to guess the name of the factors from the names of the columns. By default, ``anofa()`` will use uppercase letters to identify the factors. ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw) toCompiled(w) ``` To overcome this limit, you can manually provide factor names with ```{r, message=FALSE, warning=FALSE, echo=TRUE, eval=TRUE} w <- anofa( ~ cbind(Low,Medium,High) + cbind(Soft,Hard), dataRaw, factors = c("Intensity","Pitch") ) toCompiled(w) ``` To know more about analyzing frequency data with ANOFA, refer to @lc23b or to [What is an ANOFA?](https://dcousin3.github.io/ANOFA/articles/WhatIsANOFA.html). # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/vignettes/DataFormatsForFrequencies.Rmd
--- title: "What is Analysis of Frequency Data?" bibliography: "../inst/REFERENCES.bib" csl: "../inst/apa-6th.csl" output: rmarkdown::html_vignette description: > This vignette describes what an analysis of frequency data is. vignette: > %\VignetteIndexEntry{What is Analysis of Frequency Data?} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- The _ANalysis Of Frequency datA_ (ANOFA) is a framework for analyzing frequencies (a.k.a. counts) of classification data. This framework is very similar to the well-known ANOVA and uses the same general approach. It allows analyzing _main effects_ and _interaction effects_It also allow analyzing _simple effects_ (in case of interactions) as well as _orthogonal contrats_. Further, ANOFA makes it easy to generate frequency plots which includes confidence intervals, and to compute _eta-square_ as a measure of effect size. Finally, power planning is easy within ANOFA. ```{r, echo = FALSE, message = FALSE, results = 'hide', warning = FALSE} cat("this will be hidden; use for general initializations.\n") library(ANOFA) library(ggplot2) library(superb) # generate some random data with no meaning set.seed(43) #probs #alone #ingroup #harass #shout pr <- c(0.4/12,1.4/12,0.5/12, 2.3/12,1.0/12,0.5/12, 0.5/12,2.0/12,0.4/12, 0.5/12,2.0/12,0.5/12) dta <- GRF( list(Gender = c("boy", "girl", "other"), TypeOfInterplay = c("alone", "ingroup", "harrass", "shout") ), 300, pr ) ``` ## A basic example As an example, suppose that you observe a class of primary school students, trying to ascertain the different sorts of behaviors. You might use an obsrevation grid where, for every kid observed, you check various things, such as | Student Id: A | | |:----------------|-------------------------| |**Gender:** | Boy [**x**] Girl [ ] Other [ ] | |**Type of interplay:** | Play alone [**x**] Play in group [ ] Harrass others [ ] Shout against other [ ] | |**etc.** | This grid categorizes the participants according to two factors, `Gender`, and `TypeOfInterplay`. From these observations, one may wish to know if gender is more related to one type of interplay. Alternatively, genders could be evenly spread across types of interplay. In the second case, there is no _interaction_ between the factors. ## Some data Once collected through observations, the data can be formated in one of many ways (see the vignette [Data formats](https://dcousin3.github.io/ANOFA/articles/DataFormatsForFrequencies.html)). The raw format could look like | Id | boy | girl | other | alone | in-group | harass | shout | |----|------|-------|-------|-------|----------|--------|-------| | A | 1 | 0 | 0 | 1 | 0 | 0 | 0 | | B | 0 | 0 | 1 | 0 | 0 | 1 | 0 | | C | 0 | 1 | 0 | 0 | 0 | 0 | 1 | | D | 1 | 0 | 0 | 0 | 1 | 0 | 0 | | ...| | | | | | | | For a more compact representation, the data could be _compiled_ into a table with all the combination of gender $\times$ types of interplay, hence resulting in 12 cells. The results (totally ficticious) looks like (assuming that they are stored in a data.frame named ``dta``): ```{r, message = FALSE, warning = FALSE} dta ``` for a grand total of `r sum(dta$Freq)` childs observed. ## Analyzing the data The frequencies can be analyzed using the _Analysis of Frequency Data_ (ANOFA) framework [@lc23b]. This framework only assumes that the population is _multinomial_ (which means that the population has certain probabilities for each cell). The relevant test statistic is a $G$ statistic, whose significance is assessed using a chi-square table. *ANOFA* works pretty much the same as an *ANOFA* except that instead of looking at the means in each cell, its examines the count of observations in each cell. To run an analysis of the data frame ``dta``, simply use: ```{r, warning = FALSE} library(ANOFA) w <- anofa(Freq ~ Gender * TypeOfInterplay, data = dta) ``` This is it. The formula indicates that the counts are stored in column ``Freq`` and that the factors are ``Gender`` and ``TypeOfInterplay``, each stored in its own column. (if your data are organized differently, see [Data formats](https://dcousin3.github.io/ANOFA/articles/DataFormatsForFrequencies.html)). At this point, you might want a plot showing the counts on the vertical axis: ```{r, message=FALSE, warning=FALSE, fig.width=4, fig.height=3, fig.cap="**Figure 1**. The frequencies of the ficticious data as a function of Gender and Type of Interplay. Error bars show difference-adjusted 95% confidence intervals."} anofaPlot(w) ``` We can note a strong interaction, the `ingroup` activity not being distributed the same as a function of ``Gender``. To confirm the interaction, let's look at the ANOFA table: ```{r} summary(w) ``` Indeed, the interaction (last line) is significant ($G(6) = 65.92$, $p < .001$). The $G$ statistics is corrected for small sample but the correction is typically small (as seen in the fourth column). We might want to examine whether the frequencies of interplay are equivalent separately for each ``Gender``, even though examination of the plot suggest that it is only the case for the ``other`` gender. This is achieved with an analysis of the _simple effects_ of `TypeOfInterplay` within each level of `Gender`: ```{r} e <- emFrequencies(w, Freq ~ TypeOfInterplay | Gender) summary(e) ``` As seen, for boys and girls, the type of interplay differ significantly (both $p < .002$); for ``others``, as expected from the plot, this is not the case ($G(3) = 1.57$, $p = 0.46$). If really, you need to confirm that the major difference is caused by the ``ingroup`` type of activity (in these ficticious data), you could follow-up with a contrast analysis. We might compare `alone` to `harass`, both to `shout`, and finally the three of them to `ingroup`. ```{r} f <- contrastFrequencies(e, list( "alone vs. harass " = c(-1, 0, +1, 0 ), "(alone & harass) vs. shout " = c(-1/2, 0, -1/2, +1 ), "(alone & harass & shout) vs. in-group" = c(-1/3, +1, -1/3, -1/3) )) summary(f) ``` Because the contrast analysis is based on the simple effects within ``Gender`` (variable ``e``), we get three contrasts for each gender. As seen, for boys, `in-group` is the sole condition triggering the difference. Same for girls. Finally, there are no difference for the last group. ## Additivity of the decomposition (optional) The main advandage of ANOFA is that all the decomposition are entirely additive. If, for example, you sum the $G$s and degrees of freedom of the contrasts, with e.g., ```{r, results="hold"} sum(summary(f)[,1]) # Gs sum(summary(f)[,2]) # degrees of freedom ``` you get exacly the same as the simple effects: ```{r, results="hold"} sum(summary(e)[,1]) # Gs sum(summary(e)[,2]) # degrees of freedom ``` which is also the same as the main analysis done first, adding the main effect of ``TypeOfInterplay`` and its interaction with ``Gender`` (lines 3 and 4): ```{r, results="hold"} sum(summary(w)[c(3,4),1]) # Gs sum(summary(w)[c(3,4),2]) # degrees of freedom ``` In other words, **the decompositions preserved all the information available**. This is the defining characteristic of ANOFA. # References
/scratch/gouwar.j/cran-all/cranData/ANOFA/vignettes/WhatIsANOFA.Rmd
ANOM <- function(mc, xlabel=NULL, ylabel=NULL, printn=TRUE, printp=TRUE, stdep=NULL, stind=NULL, pst=NULL, pbin=NULL, bg="white", bgrid=TRUE, axlsize=18, axtsize=25, npsize=5, psize=5, lwidth=1, dlstyle="dashed", fillcol="darkgray"){ if(!(class(mc)[1] %in% c("glht", "SimCi", "mctp", "binomRDci"))){ stop("Please insert an object of class 'glht', 'SimCi', 'mctp', or 'binomRDci' for mc!") } if(class(mc)[1]=="glht"){ if(mc$type!="GrandMean"){ stop("For ANOM you need a 'GrandMean' contrast matrix!") } modclass <- attr(mc$model, "class")[1] if(modclass=="aov" | modclass=="lm" | modclass=="glm"){ dd <- attr(attr(mc$model$terms, "factors"), "dimnames")[[1]][1] ii <- attr(attr(mc$model$terms, "factors"), "dimnames")[[1]][2] dep <- mc$model$model[dd][, 1] ind <- mc$model$model[ii][, 1] } if(modclass=="lme"){ dd <- attr(attr(mc$model$terms, "factors"), "dimnames")[[1]][1] ii <- attr(attr(mc$model$terms, "factors"), "dimnames")[[1]][2] dep <- mc$model$data[, dd] ind <- mc$model$data[, ii] } if(modclass=="lmerMod"){ dd <- rownames(attr(attr(mc$model@frame, "terms"), "factors"))[1] ii <- rownames(attr(attr(mc$model@frame, "terms"), "factors"))[2] dep <- mc$model@frame[, dd] ind <- mc$model@frame[, ii] } ss <- as.vector(tapply(ind, ind, length)) ci <- confint(mc) if(modclass!="glm"){ means <- as.vector(tapply(dep, ind, mean)) mea <- mean(dep) } if(modclass=="glm"){ if(mc$model$family$family=="poisson"){ cit <- apply(ci$confint, 2, poisson()$linkinv) m <- mean(poisson()$linkinv(predict(mc$model))) } if(mc$model$family$family=="binomial"){ cit <- apply(ci$confint, 2, binomial()$linkinv) m <- mean(binomial()$linkinv(predict(mc$model))) } } if(is.null(xlabel)==TRUE){ xlabel <- ii }else{ xlabel <- xlabel } if(is.null(ylabel)==TRUE){ ylabel <- dd }else{ ylabel <- ylabel } if(printp==TRUE){ pvals <- summary(mc)$test$pvalues[1:length(ss)] }else{ pvals <- NULL } bg <- match.arg(bg, choices=c("gray", "grey", "white")) if(modclass!="glm"){ if(modclass=="lmerMod"){ ANOMgen(mu=means, n=ss, lo=ci$confint[, "lwr"], up=ci$confint[, "upr"], names=levels(mc$model@frame[, ii]), alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) }else{ ANOMgen(mu=means, n=ss, lo=ci$confint[, "lwr"], up=ci$confint[, "upr"], names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } } if(modclass=="glm"){ if(mc$model$family$family=="poisson"){ if(mc$alternative=="two.sided"){ ANOMintern(mu=m*cit[, 1], n=ss, gm=m, lo=m*cit[, 2]-m, up=m*cit[, 3]-m, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } if(mc$alternative=="greater"){ ANOMintern(mu=m*cit[, 1], n=ss, gm=m, lo=m*cit[, 2]-m, up=Inf, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } if(mc$alternative=="less"){ ANOMintern(mu=m*cit[, 1], n=ss, gm=m, lo=-Inf, up=m*cit[, 3]-m, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } } if(mc$model$family$family=="binomial"){ if(mc$alternative=="two.sided"){ ANOMintern(mu=cit[, 1], n=ss, gm=m, lo=cit[ ,2]-m, up=cit[ ,3]-m, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } if(mc$alternative=="less"){ ANOMintern(mu=cit[, 1], n=ss, gm=m, lo=-Inf, up=cit[ ,3]-m, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } if(mc$alternative=="greater"){ ANOMintern(mu=cit[, 1], n=ss, gm=m, lo=cit[ ,2]-m, up=Inf, names=mc$model$xlevels[[1]], alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="glm") } } } } if(class(mc)[1]=="SimCi"){ if(mc$type!="GrandMean"){ stop("For ANOM you need a 'GrandMean' contrast matrix!") } if(is.null(stdep)==TRUE){ stop("Please insert a vector giving the values\n of the dependent variable for stdep!") } if(is.null(stind)==TRUE){ stop("Please insert a numeric vector giving the values\n of the independent variable for stind!") } if(is.numeric(stdep)==FALSE){stop("The dependent variable must be numeric.")} if((length(stdep)==length(stind))==FALSE){ stop("Dependent and independent variable must be vectors of equal length.") } stind <- as.factor(stind) ss <- as.vector(tapply(stdep, stind, length)) if(mc$test.class=="ratios"){ grame <- 100 }else{ grame <- mean(stdep) } if(is.null(xlabel)==TRUE){ xlabel <- "group" }else{ xlabel <- xlabel } if(is.null(ylabel)==TRUE){ ylabel <- mc$resp }else{ ylabel <- ylabel } if(printp==TRUE){ if(class(pst)!="SimTest"){ stop("Please insert an object of class 'SimTest' for pst,\n or set printp to 'FALSE'.") } ppp <- pst$p.val.adj[1:length(ss)] }else{ ppp <- NULL } if(mc$test.class=="ratios"){ ANOMintern(mu=100*as.vector(mc$estimate), n=ss, lo=100*as.vector(mc$lower), up=100*as.vector(mc$upper), alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=ppp, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol, whichone="ratio") }else{ ANOMgen(mu=as.vector(mc$estimate)+grame, n=ss, lo=as.vector(mc$lower), up=as.vector(mc$upper), alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=ppp, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } } if(class(mc)[1]=="mctp"){ if(mc$input$type!="UserDefined"){ stop("For ANOM you need a 'UserDefined' grand-mean-type contrast matrix!") } if(is.null(mc$Correlation)==TRUE){ stop("Set the argument 'correlation' in function 'mctp()' to 'TRUE'.") } if(is.null(xlabel)==TRUE){ xlabel <- as.character(mc$input$formula[3]) }else{ xlabel <- xlabel } if(is.null(ylabel)==TRUE){ ylabel <- as.character(mc$input$formula[2]) }else{ ylabel <- ylabel } if(printp==TRUE){ pvals <- mc$Analysis$p.Value } if(mc$input$alternative=="two.sided"){ ANOMgen(mu=mc$Data.Info$Effect, n=mc$Data.Info$Size, lo=mc$Analysis$Lower, #abs(mc$Analysis$Estimator - mc$Analysis$Lower), up=mc$Analysis$Upper, #abs(mc$Analysis$Estimator - mc$Analysis$Upper), names=colnames(mc$Contrast), alternative=mc$input$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } if(mc$input$alternative=="greater"){ ANOMgen(mu=mc$Data.Info$Effect, n=mc$Data.Info$Size, lo=mc$Analysis$Lower, #abs(mc$Analysis$Estimator - mc$Analysis$Lower), up=Inf, names=colnames(mc$Contrast), alternative=mc$input$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } if(mc$input$alternative=="less"){ ANOMgen(mu=mc$Data.Info$Effect, n=mc$Data.Info$Size, lo=Inf, up=mc$Analysis$Upper, #abs(mc$Analysis$Estimator - mc$Analysis$Upper), names=colnames(mc$Contrast), alternative=mc$input$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=pvals, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } } if(class(mc)[1]=="binomRDci"){ if(attr(mc$cmat, "type")!="GrandMean"){ stop("For ANOM you need a 'GrandMean' contrast matrix!") } if(is.null(xlabel)==TRUE){ xlabel <- "group" }else{ xlabel <- xlabel } if(is.null(ylabel)==TRUE){ ylabel <- "probability of success" }else{ ylabel <- ylabel } if(printp==TRUE){ if(class(pbin)!="binomRDtest"){ stop("Please insert an object of class 'binomRDtest' for pbin,\n or set printp to 'FALSE'.") } ppp <- pbin$p.val.adj }else{ ppp <- NULL } ANOMgen(mu=mc$p, n=mc$n, lo=mc$conf.int[, "lower"], up=mc$conf.int[, "upper"], names=mc$names, alternative=mc$alternative, xlabel=xlabel, ylabel=ylabel, printn=printn, p=ppp, bg=bg, bgrid=bgrid, axlsize=axlsize, axtsize=axtsize, npsize=npsize, psize=psize, lwidth=lwidth, dlstyle=dlstyle, fillcol=fillcol) } }
/scratch/gouwar.j/cran-all/cranData/ANOM/R/ANOM.R
ANOMgen <- function(mu, n=NULL, gm=NULL, lo, up, names=NULL, alternative="two.sided", xlabel="Group", ylabel="Endpoint", printn=TRUE, p=NULL, bg="white", bgrid=TRUE, axlsize=18, axtsize=25, npsize=5, psize=5, lwidth=1, dlstyle="dashed", fillcol="darkgray"){ if(is.null(gm)){ gm <- weighted.mean(mu, n) } if(!(is.null(n)) & !(is.null(gm))){ check <- abs(weighted.mean(mu, n) - gm) if(check > 0.01){ stop("The 'gm' value you inserted is not the grand mean\n computed from your 'mu' and 'n' values!") } } grp <- 1:length(mu) grpf <- as.factor(grp) if(!(is.null(names))){ names <- as.factor(names) }else{ names <- grpf } if(is.null(n)){ printn <- FALSE } if(!(is.null(p))){ printp <- TRUE p <- paste("p=", round(p, 3), sep="") p[p=="p=0"] <- "p<0.001" }else{ printp <- FALSE } dir <- match.arg(alternative, choices=c("two.sided", "greater", "less")) if(dir=="two.sided"){ if(all(lo==-Inf) | all(lo==-1) | all(lo==0) | all(up==1) | all(up==Inf)){ warning("Is your alternative really 'two.sided'? Doesn't seem so!") } } ldl <- gm - abs((mu - gm) - up) udl <- gm + abs((mu - gm) - lo) if(printp==TRUE){ if(printn==TRUE){ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, n, p) }else{ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, p) } }else{ if(printn==TRUE){ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, n) }else{ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names) } } bg <- match.arg(bg, choices=c("gray", "grey", "white")) if(bg=="white"){ back <- theme_bw() }else{ back <- theme_gray() } if(bgrid==TRUE){ bgr <- element_line() }else{ bgr <- element_blank() } if(dir=="two.sided"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=udl, yend=udl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=ldl, yend=ldl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="LDL", x=max(grp)+0.4, y=ldl[max(grp)], size=4, vjust=1.5) + annotate("text", label="UDL", x=max(grp)+0.4, y=udl[max(grp)], size=4, vjust=-0.75) + ylim(min(min(mu), min(ldl))-(gm-min(min(mu), min(ldl)))/5, max(max(mu), max(udl))+(max(max(mu), max(udl))-gm)/5) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="greater"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=udl, yend=udl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="UDL", x=max(grp)+0.4, y=udl[max(grp)], size=4, vjust=-0.75) + ylim((min(mu)-(gm-min(mu))/5)[1], (max(max(mu), max(udl))+(max(max(mu), max(udl))-gm)/5)[1]) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="less"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=ldl, yend=ldl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="LDL", x=max(grp)+0.4, y=ldl[max(grp)], size=4, vjust=1.5) + ylim((min(min(mu), min(ldl))-(gm-min(min(mu), min(ldl)))/5)[1], (max(mu)+(max(mu)-gm)/5)[1]) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="greater"){ npart <- geom_text(aes(y=min(mu), label=paste("n=", n, sep="")), vjust=3, size=npsize) }else{ npart <- geom_text(aes(y=min(min(mu), min(ldl)), label=paste("n=", n, sep="")), vjust=3, size=npsize) } if(dir=="less"){ ppart <- geom_text(aes(y=max(mu), label=p), vjust=-2, size=npsize) }else{ ppart <- geom_text(aes(y=max(max(mu), max(udl)), label=p), vjust=-2, size=npsize) } if(printn==TRUE){ if(printp==TRUE){ chart <- basic + npart + ppart }else{ chart <- basic + npart } }else{ if(printp==TRUE){ chart <- basic + ppart }else{ chart <- basic } } print(chart) }
/scratch/gouwar.j/cran-all/cranData/ANOM/R/ANOMgen.R
ANOMintern <- function(mu, n=NULL, gm=NULL, lo, up, names=NULL, alternative="two.sided", xlabel="Group", ylabel="Endpoint", printn=TRUE, p=NULL, bg="white", bgrid=TRUE, axlsize=18, axtsize=25, npsize=5, psize=5, lwidth=1, dlstyle="dashed", fillcol="darkgray", whichone){ whichone <- match.arg(whichone, choices=c("glm", "ratio")) bg <- match.arg(bg, choices=c("gray", "grey", "white")) if(bg=="white"){ back <- theme_bw() }else{ back <- theme_gray() } if(bgrid==TRUE){ bgr <- element_line() }else{ bgr <- element_blank() } if(whichone=="ratio"){ if(is.null(gm)){ gm <- weighted.mean(mu, n) } if(!(is.null(n)) & !(is.null(gm))){ check <- abs(weighted.mean(mu, n) - gm) if(check > 0.01){ stop("The 'gm' value you inserted is not the grand mean\n computed from your 'mu' and 'n' values!") } } } grp <- 1:length(mu) grpf <- as.factor(grp) if(!(is.null(names))){ names <- as.factor(names) }else{ names <- grpf } if(is.null(n)){ printn <- FALSE } if(!(is.null(p))){ printp <- TRUE p <- paste("p=", round(p, 3), sep="") p[p=="p=0"] <- "p<0.001" }else{ printp <- FALSE } dir <- match.arg(alternative, choices=c("two.sided", "greater", "less")) if(dir=="two.sided"){ if(all(lo==-Inf) | all(lo==-1) | all(lo==0) | all(up==1) | all(up==Inf)){ warning("Is your alternative really 'two.sided'? Doesn't seem so!") } } if(whichone=="ratio"){ ldl <- gm - abs(mu - up) udl <- gm + abs(mu - lo) }else{ ldl <- gm - abs((mu - gm) - up) udl <- gm + abs((mu - gm) - lo) } if(printp==TRUE){ if(printn==TRUE){ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, n, p) }else{ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, p) } }else{ if(printn==TRUE){ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names, n) }else{ set <- data.frame(mu, gm, lo, up, ldl, udl, grp, grpf, names) } } if(dir=="two.sided"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=udl, yend=udl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=ldl, yend=ldl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="LDL", x=max(grp)+0.4, y=ldl[max(grp)], size=4, vjust=1.5) + annotate("text", label="UDL", x=max(grp)+0.4, y=udl[max(grp)], size=4, vjust=-0.75) + ylim(min(min(mu), min(ldl))-(gm-min(min(mu), min(ldl)))/5, max(max(mu), max(udl))+(max(max(mu), max(udl))-gm)/5) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="greater"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=udl, yend=udl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="UDL", x=max(grp)+0.4, y=udl[max(grp)], size=4, vjust=-0.75) + ylim((min(mu)-(gm-min(mu))/5)[1], (max(max(mu), max(udl))+(max(max(mu), max(udl))-gm)/5)[1]) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="less"){ basic <- ggplot(set, aes(x=grpf, y=mu)) + scale_x_discrete(labels=names) + xlab(xlabel) + ylab(ylabel) + geom_rect(aes(xmin=grp-0.5, xmax=grp+0.5, ymin=ldl, ymax=udl), alpha=0.5, fill=fillcol, linetype=0) + geom_segment(aes(x=grp-0.5, xend=grp+0.5, y=ldl, yend=ldl), size=lwidth, linetype=dlstyle) + geom_segment(aes(x=0.5, xend=max(grp)+0.5, y=gm, yend=gm), size=lwidth) + geom_segment(aes(x=grp, xend=grp, y=mu, yend=gm), size=lwidth) + geom_point(size=psize) + annotate("text", label="LDL", x=max(grp)+0.4, y=ldl[max(grp)], size=4, vjust=1.5) + ylim((min(min(mu), min(ldl))-(gm-min(min(mu), min(ldl)))/5)[1], (max(mu)+(max(mu)-gm)/5)[1]) + back + theme(axis.text.x=element_text(size=axlsize), axis.text.y=element_text(size=axlsize), axis.title.x=element_text(size=axtsize), axis.title.y=element_text(size=axtsize), panel.grid=bgr) } if(dir=="greater"){ npart <- geom_text(aes(y=min(mu), label=paste("n=", n, sep="")), vjust=3, size=npsize) }else{ npart <- geom_text(aes(y=min(min(mu), min(ldl)), label=paste("n=", n, sep="")), vjust=3, size=npsize) } if(dir=="less"){ ppart <- geom_text(aes(y=max(mu), label=p), vjust=-2, size=npsize) }else{ ppart <- geom_text(aes(y=max(max(mu), max(udl)), label=p), vjust=-2, size=npsize) } if(printn==TRUE){ if(printp==TRUE){ chart <- basic + npart + ppart }else{ chart <- basic + npart } }else{ if(printp==TRUE){ chart <- basic + ppart }else{ chart <- basic } } print(chart) }
/scratch/gouwar.j/cran-all/cranData/ANOM/R/ANOMintern.R
## ----LIB, echo=FALSE, message=FALSE, warning=FALSE----------------------- library(ANOM) library(multcomp) library(ggplot2) ## ----DATAHG, message=FALSE, warning=FALSE-------------------------------- library(ANOM) data(hemoglobin) ## ----PSEUDOONEWAY, fig.cap="ANOM decision chart for the hemoglobin data based one a pseudo-one-way analysis.", fig.height=5.5---- hemoglobin$the <- as.factor(abbreviate(hemoglobin$therapy)) hemoglobin$td <- with(hemoglobin, the:drug) hemodel <- lm(level ~ td, hemoglobin) he <- glht(hemodel, mcp(td="GrandMean"), alternative="two.sided") ANOM(he, xlabel="Treatment", ylabel="Hemoglobin Level") ## ----TWOWAYIA------------------------------------------------------------ hemodel2 <- lm(level ~ drug * therapy, hemoglobin) anova(hemodel2) ## ----TWOWAY, fig.cap="ANOM decision chart for the hemoglobin data based on a two-way analysis.", fig.height=5.5---- hemodel3 <- lm(level ~ drug + therapy, hemoglobin) he3 <- glht(hemodel3, mcp(drug="GrandMean"), alternative="two.sided") ANOM(he3, xlabel="Drug", ylabel="Hemoglobin Level") ## ----INSECTSData--------------------------------------------------------- data(InsectSprays) InsectSprays$block <- as.factor(rep(1:6, each=2)) ## ----INSECTS------------------------------------------------------------- insmodel1 <- glm(count ~ spray + block, data=InsectSprays, family=quasipoisson(link="log")) summary(insmodel1)$dispersion ## ----INSECTS2------------------------------------------------------------ insmodel2 <- glm(count ~ spray + block, data=InsectSprays, family=poisson(link="log")) anova(insmodel2, test="Chisq") ## ----INSECTS2a, fig.cap="ANOM decision chart for the insect spray data based on a Poisson GLM.", fig.height=5.5---- ins <- glht(insmodel2, mcp(spray="GrandMean")) ANOM(ins) ## ----DATAES, message=FALSE, warning=FALSE-------------------------------- library(nlme) data(ergoStool) ## ----NLME, fig.cap="ANOM decision chart for the ergonomic stool data based on a linear mixed-effects model.", fig.height=5.5---- library(nlme) esmodel1 <- lme(effort ~ Type, random=~1|Subject, data=ergoStool) es1 <- glht(esmodel1, mcp(Type="GrandMean"), alternative="two.sided") ANOM(es1, xlabel="Stool Type", ylabel="Exertion (Borg Scale)") ## ----LME4, eval=FALSE---------------------------------------------------- # library(lme4) # esmodel2 <- lmer(effort ~ Type + (1|Subject), data=ergoStool) # es2 <- glht(esmodel2, mcp(Type="GrandMean"), alternative="two.sided") # ANOM(es2, xlabel="Stool Type", ylabel="Exertion (Borg Scale)") ## ----MIXIGNORE, fig.cap="ANOM decision chart for the ergonomic stool data based on a standard linear model.", fig.height=5.5---- esmodel3 <- lm(effort ~ Type, ergoStool) es3 <- glht(esmodel3, mcp(Type="GrandMean"), alternative="two.sided") ANOM(es3, xlabel="Stool Type", ylabel="Exertion (Borg Scale)")
/scratch/gouwar.j/cran-all/cranData/ANOM/inst/doc/ANOM.R
#################################################################################### #' @title ANOPA: analysis of proportions using Anscombe transform. #' #' @md #' #' @description The function 'anopa()' performs an ANOPA for designs with up to 4 factors #' according to the 'ANOPA' framework. See \insertCite{lc23;textual}{ANOPA} for more. #' #' #' @param formula A formula with the factors on the left-hand side. See below for writing the #' formula to match the data format. #' #' @param data Dataframe in one of wide, long, or compiled format; #' #' @param WSFactors For within-subjet designs, provide the factor names and their number of levels. #' This is expressed as a vector of strings such as "Moment(2)". #' #' @return An omnibus analyses of the given proportions. Each factor's significance is #' assessed, as well as their interactions when there is more than one factor. For #' decomposition of the main analyses, follow the analysis with `emProportions()`, #' `contrastProportions()`, or `posthocProportions()`) #' #' @details Note the following limitations: #' 1. The main analysis performed by `anopa()` is currently restricted to four #' factors in total (between and/or within). Contact the author if you plan to analyse #' more complex designs. #' 2. If you have repeated-measure design, the data *must* be provided in wide or #' long format. The correlation between successes cannot be assessed once the data are #' in a compiled format. #' 3. The data can be given in three formats: #' * `wide`: In the wide format, there is one line for each participant, and #' one column for each between-subject factors in the design. In the column(s), the level #' of the factor is given (as a number, a string, or a factor). For within-subject #' factors, the columns contains 0 or 1 based on the status of the measurement. #' * `long`: In the long format, there is an identifier column for each participant, #' a factor column and a level number for that factor. If there are n participants #' and m factors, there will be in total n x m lines. #' * `compiled`: In the compiled format, there are as many lines as there are cells in the #' design. If there are two factors, with two levels each, there will be 4 lines. #' #' See the vignette [`DataFormatsForProportions`](../articles/B-DataFormatsForProportions.html) #' for more on data format and how to write their formula. #' #' #' @references #' \insertAllCited #' #' @examples #' # -- FIRST EXAMPLE -- #' # Basic example using a single between-subject factor design with the data in compiled format. #' # Ficticious data present success (1) or failure (0) of the observation according #' # to the state of residency (three levels: Florida, Kentucky or Montana) for #' # 3 possible cells. There are 175 observations (with unequal n, Montana having only) #' # 45 observations). #' minimalBSExample #' # The data are in compiled format, consequently the data frame has only three lines. #' # The complete data frame in wide format would be composed of 175 lines, one per participant. #' #' # The following formula using curly braces is describing this data format #' # (note the semicolon to separate the number of successes from the number of observations): #' formula <- {s; n} ~ state #' #' # The analysis is performed using the function `anopa()` with a formula and data: #' w <- anopa(formula, minimalBSExample) #' summary(w) #' # As seen, the proportions of success do not differ across states. #' #' # To see the proportions when the data is in compiled format, simply divide the #' # number of success (s) by the total number of observations (n): #' minimalBSExample$s / minimalBSExample$n #' #' # A plot of the proportions with error bars (default 95% confidence intervals) is #' # easily obtained with #' anopaPlot(w) #' #' # The data can be re-formated into different formats with, #' # e.g., `toRaw()`, `toLong()`, `toWide()` #' head(toWide(w)) #' # In this format, only 1s and 0s are shown, one participant per line. #' # See the vignette `DataFormatsForFrequencies` for more. #' #' # -- SECOND EXAMPLE -- #' # Real-data example using a three-factor design with the data in compiled format: #' ArringtonEtAl2002 #' #' # This dataset, shown in compiled format, has three cells missing #' # (e.g., fishes whose location is African, are Detrivore, feeding Nocturnally) #' w <- anopa( {s;n} ~ Location * Trophism * Diel, ArringtonEtAl2002 ) #' #' # The function `anopa()` generates the missing cells with 0 success over 0 observations. #' # Afterwards, cells with missing values are imputed based on the option: #' getOption("ANOPA.zeros") #' # where 0.05 is 1/20 of a success over one observations (arcsine transforms allows #' # fractions of success; it remains to be studied what imputation strategy is best...) #' #' # The analysis suggests a main effect of Trophism (type of food ingested) #' # but the interaction Trophism by Diel (moment of feeding) is not to be neglected... #' summary(w) # or summarize(w) #' #' # The above presents both the uncorrected statistics as well as the corrected #' # ones for small samples [@w76]. You can obtain only the uncorrected... #' uncorrected(w) #' #' #... or the corrected ones #' corrected(w) #' #' #' # You can also ask easier outputs with: #' explain(w) # human-readable ouptut NOT YET DONE #' #################################################################################### #' #' @importFrom stats pchisq as.formula #' @importFrom utils combn #' @importFrom utils capture.output #' @export anopa #' @importFrom Rdpack reprompt #' #################################################################################### anopa <- function( formula = NULL, #mandatory: the design of the data data = NULL, #mandatory: the data itself WSFactors = NULL #optional: if the data are in raw format, name the factors ) { ############################################################################## ## NB. Herein, the following abbreviations are used ## WS: Within-subject design ## BS: Between-subject design ## MX: Mixed, within+between, design ############################################################################## ############################################################################## # STEP 0: preliminary preparations... ############################################################################## data <- as.data.frame(data) # coerce to data.frame if tibble or compatible ############################################################################## # STEP 1: Input validation ############################################################################## # 1.1: is the formula actually a valid formula? if (!is.formula(formula)) stop("ANOPA::error(11): Argument `formula` is not a legitimate formula. Exiting...") # 1.2: has the formula 1 or more DV? if (is.one.sided( formula )) { stop("ANOPA::error(12): Argument `formula` has no DV. Exiting...") } # 1.3: are the data actually data? if( (!is.data.frame(data)) || (dim(data)[2] <= 1)) stop("ANOPA::error(13): Argument `data` is not a data.frame or similar data structure. Exiting...") # 1.4: are the columns named in the formula present in the data? vars <- all.vars(formula) # extract variables, cbind and nested alike vars <- vars[!(vars == ".")] # remove . if (!(all(vars %in% names(data)))) stop("ANOPA::error(14): Variables in `formula` are not all in `data`. Exiting...") # 1.5: If wide format with repeated-measures, are the WSFactors given? if ((has.cbind.terms(formula)) && is.null(WSFactors)) stop("ANOPA::error(15): Argument `WSFactors` must be defined in wide format with repeated measures Existing...") ############################################################################## # STEP 2: Manage WS factors ############################################################################## # 2.0: Keep only the columns named data <- data[, names(data) %in% vars] # 2.1: get cbind variables if Wide (WS or MX) formats if (has.cbind.terms(formula)) { # extract vars from cbind bvars <- c() for (i in 2:length(formula[[2]])) bvars <- c(bvars, paste(formula[[2]][[i]])) cleanedWSF <- cleanWSFactors(WSFactors, bvars) } # 2.2: get WSfactors in Long format before they are erased if (has.nested.terms(formula)) { tmp <- getAroundNested(formula) wsvars <- unique(data[[paste(tmp[[2]])]]) cleanedWSF <- cleanWSFactors(WSFactors, wsvars) } ############################################################################## # STEP 3: Harmonize the data format to wide ############################################################################## # 3.1: Set defaults uAlpha <- -99.9 # no correlation BSFactors <- WSFactors <- c() WSLevels <- BSLevels <- 1 WSDesign <- data.frame() # 3.2: Convert data to wide format based on the format as infered from the formula if (in.formula(formula, "{")&& has.cbind.terms(formula)) { # Case 1: Compiled (WS or MX) template: {cbind(b1,..,bm);n;r} ~ Factors stop("ANOPA::error(16): The compiled format must not contain repeated measures. Exiting...") } else if (in.formula(formula, "{")) { #case 1: Compiled (BS only) template: {s;n} ~ Factors bracedvars <- c(paste(formula[[2]][[2]]), paste(formula[[2]][[3]])) wideData <- ctow(data, bracedvars[1], bracedvars[2] ) BSFactors <- complement(vars, bracedvars) BSLevels <- unlist(lapply(BSFactors, \(x) length(unique(wideData[,x])) )) DVvars <- paste(formula[[2]][[2]]) } else if (has.cbind.terms(formula)) { #case 2: Wide (WS or MX) # 2.1: Wide (WS) template: cbind(b1,...,bm) ~ . # 2.2: Wide (MX) template: cbind(b1,...,bm) ~ Factors BSFactors <- complement(vars, bvars) BSLevels <- unlist(lapply(BSFactors, \(x) length(unique(data[,x])) )) WSFactors <- cleanedWSF[[1]] WSLevels <- cleanedWSF[[2]] WSDesign <- cleanedWSF[[3]] DVvars <- bvars wideData <- data # nothing to do, already correct format # computes correlation with unitaryAlpha factors <- names(data)[!(names(data) %in% bvars )] if (length(factors) == 0) { # adds a dummy BS factor data[["dummyBSfactor"]] <- 1; factors <- "dummyBSfactor" } uAlpha <- plyr::ddply(data, factors, function(x) {unitaryAlpha(as.matrix(x[bvars]))} )$V1 } else if (has.nested.terms(formula)) { #case 3: long (BS or WS or MX) # 3.1: long (BS) template: b ~ BSFactors | Id # 3.2: long (WS) template: b ~ WSConditions | Id # 3.3: long (MX) template: b ~ BSFactors * WSConditions | Id idvar <- getAfterNested( formula ) DVvars <- paste(formula[[2]]) # get vars that are changing for a given Id Factors <- names(data)[ !(names(data) %in% c(idvar, DVvars))] BSFactors <- c() WSFactors <- c() for (i in Factors) { if (dim(unique(data[data[[idvar]] == 1,][c(idvar, i)]))[1] > 1) { WSFactors <- c(WSFactors, i) } else { BSFactors <- c(BSFactors, i) } } wideData <- ltow(data, idvar, tmp[[2]], DVvars ) # take the success name under Variable DVvars <- names(wideData)[!(names(wideData) %in% c( all.vars(formula[[3]]), "n"))] BSFactors <- complement(names(wideData), DVvars) BSLevels <- unlist(lapply(BSFactors, \(x) length(unique(wideData[,x])) ) ) WSFactors <- cleanedWSF[[1]] WSLevels <- cleanedWSF[[2]] WSDesign <- cleanedWSF[[3]] # computes correlation with unitaryAlpha if (!is.null(WSFactors)) { factors <- names(wideData)[!(names(wideData) %in% wsvars )] if (length(factors) == 0) { # adds a dummy BS factor wideData[["dummyBSfactor"]] <- 1; factors <- "dummyBSfactor" } uAlpha <- plyr::ddply(wideData, factors, function(x) {unitaryAlpha(as.matrix(x[wsvars]))} )$V1 wideData[["dummyBSfactor"]] <- NULL } } else if (length(formula[[1]]) == 1) { #case 2.3: Wide (BS) template: b ~ Factors wideData <- data # nothing to do, already correct format # extract vars from rhs formula BSFactors <- all.vars(formula[[3]]) BSLevels <- unlist(lapply(BSFactors, \(x) length(unique(wideData[,x])) ) ) WSLevels <-1 DVvars <- paste(formula[[2]]) } else { # error... stop("ANOPA::error(17): Unrecognized data format. Exiting...") } # 3.3: Keep the factor names allFactors <- c(WSFactors, BSFactors) # 3.4: Acknolwedge limitations of the present package if( (length(allFactors) < 1) ) stop("ANOPA::error(18a): No factor provided. Exiting...") if( (length(allFactors)>4) || (length(allFactors) < 1) ) stop("ANOPA::error(18b): Too many factors. Exiting...") if( length(allFactors)==4 ) stop("ANOPA::error(18c): Four factors; contact the author. Exiting...") ############################################################################## # STEP 4: run the analysis, depending on the number of factors ############################################################################## # 4.0: additional checks on within... if (prod(WSLevels) != length(DVvars)) stop("ANOPA::error(19): There are missing within-subject level columns. Exiting...") # 4.1: to avoid integer overflow, convert integers to num for (i in DVvars) wideData[[i]] <- as.numeric( wideData[[i]] ) # 4.2: compile the data compData <- wtoc(wideData, DVvars, "n") # 4.3: check for all sorts of missing (not there or there with zeros...) compData <- checkmissingcellsBSFactors(compData, BSFactors, DVvars) compData <- checkforZeros(compData, DVvars) # 4.4: sort the data if (length(BSFactors) > 0) compData <- compData[ do.call(order, data.frame(compData[,BSFactors]) ), ] # 4.4: perform the analysis based on the number of factors analysis <- switch( length(allFactors), anopa1way(compData, DVvars, "n", BSFactors, WSFactors, WSLevels), anopa2way(compData, DVvars, "n", BSFactors, WSFactors, WSLevels), anopa3way(compData, DVvars, "n", BSFactors, WSFactors, WSLevels), anopa4way(compData, DVvars, "n", BSFactors, WSFactors, WSLevels) ) ############################################################################## # STEP 5: return the object ############################################################################## # 5.1: preserve everything in an object of class ANOPAobject res <- list( type = "ANOPAomnibus", formula = as.formula(formula), BSfactColumns = BSFactors, BSfactNlevels = BSLevels, WSfactColumns = WSFactors, WSfactDesign = WSDesign, WSfactNlevels = WSLevels, DVvariables = DVvars, wideData = wideData, # raw data are absolutely needed for plot only compData = compData, # compiled data are used for analyzes omnibus = analysis # results of the omnibus analysis ) class(res) <- c("ANOPAobject", class(res) ) return( res ) } ############################################################################## # Subfunctions ############################################################################## getAfterNested <- function(frm) { # There are three possible cases? # frm1 <- b ~ BSFactors * WSConditions | Id # frm2 <- b ~ WSConditions | Id * BSFactors # frm3 <- b ~ (WSConditions | Id) * BSFactors f <- sub.formulas(frm, "|")[[1]] if (length(f[[3]]) == 1) { v1 <- f[[3]] } else { if (f[[3]][[1]] == "*") { v1 <- f[[3]][[2]] } else { stop("ANOPA::internal(-1): Case non-existant: That should never happen") } } return( paste(v1) ) } getAroundNested <- function(frm) { # There are three possible cases? # frm1 <- b ~ BSFactors * WSConditions | Id # frm2 <- b ~ WSConditions | Id * BSFactors # frm3 <- b ~ (WSConditions | Id) * BSFactors f <- sub.formulas(frm, "|")[[1]] if (length(f[[3]]) == 1) { v1 <- f[[3]] if (length(f[[2]]) == 1) { v2 <- f[[2]] } else { v2 <- f[[2]][[length(f[[2]])]] } } else { if (f[[3]][[1]] == "*") { v1 <- f[[3]][[2]] if (length(f[[2]]) == 1) { v2 <- f[[2]] } else { v2 <- f[[2]][[length(f[[2]])]] } } else { stop("ANOPA::internal (-2): Case non-existant: That should never happen") } } return( c( paste(v1), paste(v2)) ) } checkforZeros <- function( cData, ss) { # Are there emtpy cells, i.e. where the proportion is 0 on 0? # These must be imputed to avoid Undetermined scores # Adjust ANOPA.zeros vector for a different imputation strategy # DISCLAIMER: I did not validate if this is a sensible strategy. Do your homework. res <- cData repl <- as.list(unlist(options("ANOPA.zeros"))) # niaisage... for (i in ss) { if (any(mapply(\(x,y){(x==0)&&(y==0)}, res[[i]], res[["n"]]) ) ) { ANOPAwarning("ANOPA::warning(1): Some cells have zero over zero data. Imputing...") res[ res[[i]] == 0 & res[["n"]] == 0, c(i,"n")] <- repl } } return( res ) } checkmissingcellsBSFactors <- function( cData, BSFactors, ss) { # all the combination of the levels of the factors a <- prod(unlist(lapply(BSFactors, \(x) length(unique(cData[,x]))))) b <- dim(cData)[1] if (a != b) { # there are missing cases lvls <- lapply(BSFactors, \(x) unique(cData[,x])) cmbn <- expand.grid(lvls) names(cmbn) <- BSFactors notthere <- linesA1notInA2( cmbn, cData ) for ( m in ss ) {notthere[[m]] <- 0} notthere[["n"]] <- 0 cData <- rbind(cData, notthere) ANOPAmessage(paste("ANOPA::fyi(1): Combination of cells missing. Adding: ")) temp <- paste0(capture.output(print(notthere, row.names=FALSE)),collapse="\n") ANOPAmessage(temp) } return( cData ) } cleanWSFactors <- function(WSFactors, ss) { # Unpack the WS factors and run a fyi if not inhibited... WSLevels <- c(1) WSDesign <- data.frame() if (!is.null(WSFactors)) { # separate name from nLevel for (i in 1:length(WSFactors)) { WSLevels[i] <- as.integer(unlist(strsplit(WSFactors[i], '[()]'))[2]) WSFactors[i] <- unlist(strsplit(WSFactors[i], '[()]'))[1] } combinaisons <- expand.grid(lapply(WSLevels, seq)) WSDesign <- cbind(combinaisons, ss) colnames(WSDesign)[1:length(WSFactors)] <- WSFactors colnames(WSDesign)[length(WSFactors)+1] <- "Variable" if ( (!is.null(WSFactors)) & ('design' %in% getOption("ANOPA.feedback") ) ) { ANOPAmessage("ANOPA::fyi: Here is how the within-subject variables are understood:") temp <- paste0(capture.output(print(WSDesign[,c(WSFactors, "Variable") ], row.names=FALSE)),collapse="\n") ANOPAmessage(temp) } } return( list(WSFactors, WSLevels, WSDesign ) ) } # disjonction of two data.frames linesA1notInA2 <- function( a1, a2 ) { # adds dummy columns a1$included_a1 <- TRUE a2$included_a2 <- TRUE res <- merge(a1, a2, all=TRUE) res <- res[ is.na(res$included_a2), ] # removes the dummy columns res$included_a1 <- NULL res$included_a2 <- NULL return( res ) } # harmonic mean hmean <- function(v) (length(v)/ sum(1/v)) ############################################################################## # Analyses functions per se ############################################################################## anopa1way <- function( cData, ss, n, bsfacts, wsfacts, unneeded ) { # One-way ANOPA (either within- or between-subject design) # The observations are compiled into success (s) and number (n) per group and uAlpha when relevant if (length(wsfacts) == 1) { # within-subject design s <- cData[ss] n <- rep(cData[[n]], length(ss)) facts <- wsfacts corlt <- cData[["uAlpha"]] } else { # between-subject design s <- cData[[ss]] n <- cData[[n]] facts <- bsfacts corlt <- 0 } # apply the transform to all the pairs (s, n) As <- mapply(A, s, n) Vs <- mapply(varA, s, n) p <- length(As) # compute mean square of effect P, mean square of error msP <- var(As) msE <- mean(Vs) * (1-corlt) # compute F ratio or chi-square test statistic F <- msP / msE g <- (p-1) * F # compute p value from the latter (the former has infinite df on denominator) pval <- 1 - pchisq(g, df = (p-1) ) # the corrections cf <- 1+ (p^2-1)/(6 * hmean(n) * (p-1) ) pvaladj <- 1 - pchisq(g/cf, df = (p-1) ) # keep the results results <- data.frame( MS = c(msP, msE), df = c(p-1,Inf), F = c(F, NA), p = c(pval, NA), correction = c(cf,NA), Fcorr = c(g/cf/(p-1),NA), pvalcorr = c(pvaladj, NA) ) rownames(results) <- c(facts, "Error") return(results) } anopa2way <- function( cData, ss, n, bsfacts, wsfacts, wslevls ) { # Two-way ANOPA (within, between, or mixed design) # the observations are compiled into success (s) and number (n) per group and uAlpha when relevant if (length(wsfacts) == 2) { # both within-subject factors s <- cData[ss] n <- rep(cData[[n]], length(ss)) corlt <- cData[["uAlpha"]] facts <- wsfacts f1levl <- wslevls[2] } else if (length(wsfacts) == 1) { # mixed, within-between, design s <- unlist(cData[ss]) # i.e., flatten n <- rep(cData[[n]], length(ss)) corlt <- rep(cData[["uAlpha"]], wslevls[1]) facts <- c(wsfacts, bsfacts) f1levl <- wslevls } else { # both between-subject factors s <- cData[[ss]] n <- cData[[n]] corlt <- 0 facts <- bsfacts f1levl <- length(unique(cData[[bsfacts[1]]])) } # apply the transform to all the pairs (s, n) As <- mapply(A, s, n) Vs <- mapply(varA, s, n) # fold the scores into a matrix Af <- matrix( As, ncol = f1levl) Vf <- matrix( Vs, ncol = f1levl) ns <- matrix( n, ncol = f1levl) # compute marginal means (P is "column" factor, Q is "row" factor) and grand mean AP <- colMeans(Af) # marginal mean along Q factor AQ <- rowMeans(Af) # marginal mean along P factor Ag <- mean(As) # grand mean nP <- colSums(ns) # sample size across all Q levels nQ <- colSums(t(ns)) # sample size across all P levels p <- length(AP) q <- length(AQ) # compute mean square of effects P, Q and PxQ msP <- q * var( AP ) msQ <- p * var( AQ ) msPQ <- 1/((p-1)*(q-1)) * sum((As - outer(AQ, AP, `+`) + mean(As) )^2 ) # get mean squared of error for within and between respectively msEintra <- 1/(p*q) * sum( (1-corlt)/(4*(ns+1/2) ) ) msEinter <- 1/(p*q) * sum( 1 / (4*(ns+1/2)) ) # assign error terms to each factor based on design msEp <- if (facts[1] %in% wsfacts) msEintra else msEinter msEq <- if (facts[2] %in% wsfacts) msEintra else msEinter msEpq <- if ((facts[1] %in% wsfacts)|(facts[2] %in% wsfacts)) msEintra else msEinter # compute F ratio or chi-square test statistic FP <- msP/msEp FQ <- msQ/msEq FPQ <- msPQ/msEpq gP <- (p-1) * FP gQ <- (q-1) * FQ gPQ <- (p-1) * (q-1) * FPQ # compute p value from the latter (the former has infinite df on denominator) pvalP <- 1 - pchisq(gP, df = (p-1) ) pvalQ <- 1 - pchisq(gQ, df = (q-1) ) pvalPQ <- 1 - pchisq(gPQ, df = (p-1) * (q-1) ) # If you want to apply the corrections cfP <- 1 + (p^2-1)/(6 * hmean(nP) * (p-1) ) cfQ <- 1 + (q^2-1)/(6 * hmean(nQ) * (q-1) ) cfPQ <- 1 + ((p * q)^2-1)/(6 * hmean(ns) * (p-1)*(q-1) ) pvalPadj <- 1 - pchisq(gP/cfP, df = (p-1) ) pvalQadj <- 1 - pchisq(gQ/cfQ, df = (q-1) ) pvalPQadj <- 1 - pchisq(gPQ/cfPQ, df = (p-1)*(q-1) ) # keep the results results <- data.frame( MS = c(msP, msQ, msPQ, msEintra, msEinter ), df = c(p-1, q-1, (p-1)*(q-1), Inf, Inf ), F = c(FP, FQ, FPQ, NA, NA ), pvalue = c(pvalP, pvalQ, pvalPQ, NA, NA ), correction = c(cfP, cfQ, cfPQ, NA, NA ), Fcorr = c(FP/cfP, gQ/cfQ/(q-1), gPQ/cfPQ/((p-1)*(q-1)), NA, NA ), pvalcorr = c(pvalPadj, pvalQadj, pvalPQadj, NA, NA) ) rownames(results) <- c(facts, paste(facts, collapse=":"), "Error(within)", "Error(between)" ) if (length(bsfacts) == 0) results <- results[-5,] #remove 5th line if (length(wsfacts) == 0) results <- results[-4,] #remove 4th line return(results) } anopa3way <- function( cData, ss, n, bsfacts, wsfacts, wslevls ) { # Three-way ANOPA (any design with within or between subject factors) # the observations are compiled into success (s) and number (n) per group and uAlpha when relevant if (length(wsfacts) == 3) { # entirely within-subject factors s <- cData[ss] n <- rep(cData[[n]], length(ss)) corlt <- cData[["uAlpha"]] facts <- wsfacts lvlp <- 1:wslevls[1] # first is always within lvlq <- 1:wslevls[2] lvlr <- 1:wslevls[3] p <- length(lvlp) q <- length(lvlq) r <- length(lvlr) } else if (length(wsfacts) == 2) { # mixed, 2 within-subject factors s <- cData[ss] n <- rep(cData[[n]], length(ss)) corlt <- cData[["uAlpha"]] facts <- c(wsfacts, bsfacts) lvlp <- 1:wslevls[1] lvlq <- 1:wslevls[2] lvlr <- unique(cData[[bsfacts[1]]]) p <- length(lvlp) q <- length(lvlq) r <- length(lvlr) corlt <- array(unlist(lapply( corlt, rep, p*q)), dim = c(r,q,p)) } else if (length(wsfacts) == 1) { # mixed, 1 within-subject factor s <- c(t(cData[ss])) # i.e., flatten n <- rep(cData[[n]], length(ss)) corlt <- rep(cData[["uAlpha"]], wslevls[1]) facts <- c(wsfacts, bsfacts) lvlp <- 1:wslevls[1] lvlq <- unique(cData[[bsfacts[1]]]) lvlr <- unique(cData[[bsfacts[2]]]) p <- length(lvlp) q <- length(lvlq) r <- length(lvlr) corlt <- array(unlist(lapply( corlt, rep, p)), dim = c(r,q,p)) } else { # entirely between-subject factors s <- cData[[ss]] n <- cData[[n]] corlt <- 0 facts <- bsfacts lvlp <- unique(cData[[bsfacts[1]]]) lvlq <- unique(cData[[bsfacts[2]]]) lvlr <- unique(cData[[bsfacts[3]]]) p <- length(lvlp) q <- length(lvlq) r <- length(lvlr) } # apply the transform to all the pairs (s, n) As <- mapply(A, s, n) Vs <- mapply(varA, s, n) # fold the scores into an array # for between-subject design: https://stackoverflow.com/a/52435862/5181513 namesOfDim <- list( lvlr, lvlq, lvlp ) Af <- array(As, dim = c(r, q, p), dimnames = namesOfDim) Vf <- array(Vs, dim = c(r, q, p), dimnames = namesOfDim) ns <- array(n, dim = c(r, q, p), dimnames = namesOfDim) # compute marginal means (P is "column" factor, Q is "row" factor) and grand mean AP <- apply(Af, 3, mean) AQ <- apply(Af, 2, mean) AR <- apply(Af, 1, mean) APQ <- apply( Af, c(3,2), mean ) ## Les dimensions sont inversées APR <- apply( Af, c(3,1), mean ) AQR <- apply( Af, c(2,1), mean ) nP <- apply( ns, 3, sum ) # sample size across all R levels nQ <- apply( ns, 2, sum ) # sample size across all R levels nR <- apply( ns, 1, sum ) # sample size across all R levels nPQ <- apply( ns, c(3,2), sum ) # sample size across all R levels nPR <- apply( ns, c(3,1), sum ) # sample size across all R levels nQR <- apply( ns, c(2,1), sum ) # sample size across all R levels # compute mean square of effects P, Q and PxQ; Keppel, 1978 msP <- q*r * var( AP ) msQ <- p*r * var( AQ ) msR <- p*q * var( AR ) msPQ <- ((p*q-1) * r * var( c(APQ) ) - (p-1)*msP - (q-1)*msQ)/((p-1)*(q-1)) msPR <- ((p*r-1) * q * var( c(APR) ) - (p-1)*msP - (r-1)*msR)/((p-1)*(r-1)) msQR <- ((q*r-1) * p * var( c(AQR) ) - (q-1)*msQ - (r-1)*msR)/((q-1)*(r-1)) msPQR <- ((p*q*r-1)*var( c(Af) ) -(p-1)*(q-1)*msPQ -(p-1)*(r-1)*msPR -(q-1)*(r-1)*msQR -(p-1)*msP -(q-1)*msQ -(r-1)*msR )/ ((p-1)*(q-1)*(r-1)) # get mean squared of error for within and between respectively msEintra <- 1/(p*q*r)*sum( (1-corlt)/ (4*ns+1/2)) msEinter <- 1/(p*q*r)*sum( 1 / (4*ns+1/2)) # assign error terms to each factor based on design msEp <- if (facts[1] %in% wsfacts) msEintra else msEinter msEq <- if (facts[2] %in% wsfacts) msEintra else msEinter msEr <- if (facts[3] %in% wsfacts) msEintra else msEinter msEpq <- if ((facts[1] %in% wsfacts)|(facts[2] %in% wsfacts)) msEintra else msEinter msEpr <- if ((facts[1] %in% wsfacts)|(facts[3] %in% wsfacts)) msEintra else msEinter msEqr <- if ((facts[2] %in% wsfacts)|(facts[3] %in% wsfacts)) msEintra else msEinter msEpqr <- if ((facts[1] %in% wsfacts)|(facts[2] %in% wsfacts)|(facts[3] %in% wsfacts)) msEintra else msEinter # compute F ratio or chi-square test statistic FP <- msP/msEp FQ <- msQ/msEq FR <- msR/msEr FPQ <- msPQ/msEpq FPR <- msPR/msEpr FQR <- msQR/msEqr FPQR <- msPQR/msEpqr gP <- (p-1) * FP gQ <- (q-1) * FQ gR <- (r-1) * FR gPQ <- (p-1) * (q-1) * FPQ gPR <- (p-1) * (r-1) * FPR gQR <- (q-1) * (r-1) * FQR gPQR <- (p-1) * (q-1) * (r-1) * FPQR # compute p value from the latter (the former has infinite df on denominator) pvalP <- 1 - pchisq(gP, df = (p-1) ) pvalQ <- 1 - pchisq(gQ, df = (q-1) ) pvalR <- 1 - pchisq(gR, df = (r-1) ) pvalPQ <- 1 - pchisq(gPQ, df = (p-1) * (q-1) ) pvalPR <- 1 - pchisq(gPR, df = (p-1) * (r-1) ) pvalQR <- 1 - pchisq(gQR, df = (q-1) * (r-1) ) pvalPQR <- 1 - pchisq(gPQR, df = (p-1) * (q-1) * (r-1) ) # If you want to apply the corrections; we remove the imputed cells... cfP <- 1 + (p^2-1)/(6 * hmean(nP) * (p-1) ) cfQ <- 1 + (q^2-1)/(6 * hmean(nQ) * (q-1) ) cfR <- 1 + (r^2-1)/(6 * hmean(nR) * (r-1) ) cfPQ <- 1 + ((p * q)^2-1)/(6 * hmean(ns[ns>1]) * (p-1)*(q-1) ) cfPR <- 1 + ((p * r)^2-1)/(6 * hmean(ns[ns>1]) * (p-1)*(r-1) ) cfQR <- 1 + ((q * r)^2-1)/(6 * hmean(ns[ns>1]) * (q-1)*(r-1) ) cfPQR <- 1 + ((p * q * r)^2-1)/(6 * hmean(ns[ns>1]) * (p-1)*(q-1)*(r-1) ) pvalPadj <- 1 - pchisq(gP/cfP, df = (p-1) ) pvalQadj <- 1 - pchisq(gQ/cfQ, df = (q-1) ) pvalRadj <- 1 - pchisq(gR/cfR, df = (r-1) ) pvalPQadj <- 1 - pchisq(gPQ/cfPQ, df = (p-1)*(q-1) ) pvalPRadj <- 1 - pchisq(gPR/cfPR, df = (p-1)*(r-1) ) pvalQRadj <- 1 - pchisq(gQR/cfQR, df = (q-1)*(r-1) ) pvalPQRadj <- 1 - pchisq(gPQR/cfPQR, df = (p-1)*(q-1)*(r-1) ) # keep the results results <- data.frame( MS = c(msP, msQ, msR, msPQ, msPR, msQR, msPQR, msEintra, msEinter ), df = c(p-1, q-1, r-1, (p-1)*(q-1), (p-1)*(r-1), (q-1)*(r-1), (p-1)*(q-1)*(r-1), Inf, Inf ), F = c(FP, FQ, FR, FPQ, FPR, FQR, FPQR, NA, NA ), pvalue = c(pvalP, pvalQ, pvalR, pvalPQ, pvalPR, pvalQR, pvalPQR, NA, NA ), correction = c(cfP, cfQ, cfR, cfPQ, cfPR, cfQR, cfPQR, NA, NA ), Fcorr = c(FP/cfP, gQ/cfQ/(q-1), gR/cfR/(r-1), gPQ/cfPQ/((p-1)*(q-1)), gPR/cfPR/((p-1)*(r-1)), gQR/cfQR/((q-1)*(r-1)), gPQR/cfPQR/((p-1)*(q-1)*(r-1)), NA, NA ), pvalcorr = c(pvalPadj, pvalQadj, pvalRadj, pvalPQadj, pvalPRadj, pvalQRadj, pvalPQRadj, NA, NA) ) rownames(results) <- c(facts, apply(data.frame(utils::combn(facts,2)), 2, paste, collapse = ":"), paste(facts, collapse=":"), "Error(within)", "Error(between)" ) if (length(bsfacts) == 0) results <- results[-9,] #remove between-error line if (length(wsfacts) == 0) results <- results[-8,] #remove within-error line return(results) } anopa4way <- function( cData, ss, n, bsfacts, wsfacts, wslevls ) { return("Not programmed so far. Contact Denis Cousineau if needed.") }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-anopa.R
###################################################################################### #' @title contrastProportion: analysis of contrasts between proportions using Anscombe transform. #' #' @md #' #' @description The function 'contrastProportions()' performs contrasts analyses #' on proportion data after an omnibus analysis has been obtained with 'anopa()' #' according to the ANOPA framework. See \insertCite{lc23;textual}{ANOPA} for more. #' #' @param w An ANOPA object obtained from `anopa()` or `emProportions()`; #' #' @param contrasts A list that gives the weights for the contrasts to analyze. #' The contrasts within the list can be given names to distinguish them. #' The contrast weights must sum to zero and their cross-products must equal 0 #' as well. #' #' @return A table of significance of the different contrasts. #' #' @details `contrastProportions()` computes the _F_s for the contrasts, #' testing the hypothesis that it equals zero. #' The contrasts are each 1 degree of freedom, and the sum of the contrasts' #' degrees of freedom totalize the effect-being-decomposed's degree of freedom. #' #' @references #' \insertAllCited{} #' #' @examples #' # Basic example using a one between-subject factor design with the data in compiled format. #' # Ficticious data present success or failure of observation classified according #' # to the state of residency (three levels); 175 participants have been observed in total. #' #' # The cells are unequal: #' minimalBSExample #' #' # First, perform the omnibus analysis : #' w <- anopa( {s;n} ~ state, minimalBSExample) #' summary(w) #' #' # Compare the first two states jointly to the third, and #' # compare the first to the second state: #' cw <- contrastProportions( w, list( #' contrast1 = c(1, 1, -2)/2, #' contrast2 = c(1, -1, 0) ) #' ) #' summary(cw) #' # # Example using the Arrington et al. (2002) data, a 3 x 4 x 2 design involving # # Location (3 levels), Trophism (4 levels) and Diel (2 levels). # ArringtonEtAl2002 # # # performs the omnibus analysis first (mandatory): # w <- anopa( {s;n} ~ Location * Trophism * Diel, ArringtonEtAl2002) # corrected(w) # # # execute the simple effect of Trophism for every levels of Diel and Location # e <- emProportions(w, ~ Trophism | Diel * Location) # summary(e) # # # For each of these sub-cells, contrast the four tropisms, first # # by comparing the first two levels to the third (contrast1), second # # by comparing the first to the second level (contrast2), and finally by # # by comparing the first three to the last (contrast3) : # f <- contrastProportions( e, list( # contrast1 = c(1, 1, -2, 0)/2, # contrast2 = c(1, -1, 0, 0), # contrast3 = c(1, 1, 1, -3)/3 # ) # ) # summary(f) #' #' ###################################################################################### #' #' @export contrastProportions # ###################################################################################### contrastProportions <- function( w = NULL, contrasts = NULL ){ ############################################################################## ## STEP 1: VALIDATION OF INPUT ############################################################################## # 1.1: Is w of the right type if (!("ANOPAobject" %in% class(w))) stop("ANOPA::error(31): The argument w is not an ANOPA object. Exiting...") # 1.2: Are the contrasts of the right length if (min(unlist(lapply(contrasts, length))) != max(unlist(lapply(contrasts, length)))) stop("ANOPA::error(32): The constrasts have differing lengths. Exiting...") relevantlevels = if (w$type == "ANOPAomnibus") { prod( c(w$BSfactNlevels, w$WSfactNlevels) ) } else { stop("ANOPA::oups(1): This part not yet done. Exiting...") } print(relevantlevels) if (!(all(unlist(lapply(contrasts, length)) == relevantlevels ))) stop("ANOPA::error(33): The contrats lengths does not match the number of levels. Exiting...") # 1.3a: Are the contrasts legitimate (a) sum to zero; if (!(all(round(unlist(lapply(contrasts,sum)),8)==0))) stop("ANOPA::error(34): Some of the constrats do not sum to 0. Exiting...") # 1.3b: Are the contrasts legitimate (b) cross-product sum to zero sums = c() for (i in names(contrasts)) {for (j in setdiff(names(contrasts), i)) { sums <-append(sums, round(sum(contrasts[[i]]*contrasts[[j]]) ),8) } } if (!(all(sums == 0))) stop("ANOPA::error(35): Some of the cross-products of contrasts do not totalize 0. Exiting...") # 1.3c: Are the contrasts legitimate (c) all oppositions sum to 1 if (!(all(round(unlist(lapply(contrasts, \(x) sum(abs(x)))),8)==2))) stop("ANOPA::error(36): Some of the contrasts' weigth does not equal 1 (for the positive weights) or -1 (for the negative weights). Exiting...") # 1.4: is there an acceptable number of contrasts if (length(contrasts) > relevantlevels-1) stop("ANOPA::error(37): There are more contrasts defined than degrees of freedom. Exiting...") ############################################################################## ## STEP 2: Run the analysis ############################################################################## # 2.1: identify the factors ANOPAmessage("Not yet programmed...") return(-99) # 2.2: perform the analysis based on ??? analysis <- if(w$type == "ANOPAomnibus") { ## Contrasts on the full design cst1way(w$compiledData, w$freqColumn, contrasts) } else { # "ANOPAsimpleeffects" ## Contrasts on sub-data based on nesting factor(s) cstMway(w$compiledData, w$freqColumn, w$subFactors, w$nestedFactors, contrasts) } ############################################################################## # STEP 3: Return the object ############################################################################## # 3.1: preserve everything in an object of class ANOPAobject res <- list( type = "ANOPAcontrasts", formula = as.formula(w$formula), compiledData = w$compiledData, freqColumn = w$freqColumn, factColumns = w$factColumns, nlevels = w$nlevels, clevels = w$clevels, # new information added results = analysis ) class(res) <- c("ANOPAobject", class(res) ) return( res ) } ########################################## # # # ██╗ ██╗███████╗██████╗ ███████╗ # # ██║ ██║██╔════╝██╔══██╗██╔════╝ # # ███████║█████╗ ██████╔╝█████╗ # # ██╔══██║██╔══╝ ██╔══██╗██╔══╝ # # ██║ ██║███████╗██║ ██║███████╗ # # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ # # # ########################################## # Coding contrast effects # # is postponed until interest is shown. # ########################################## # ################################################################ # # Lets run the orthogonal contrasts # # ################################################################ # there is only two possible cases: # a) the contrasts are on the full data ==> cst1way # b) the contrasts are nested with some factor(s) ==> cstMway cst1way <- function(cData, ss, contrasts) { # extract the proportions and the total # get the F statistics for each contrast # compute the correction factor cf # compute the p values on the corrected G as usual # This is it! let's put the results in a table } cstMway <- function(cData, ss, subfact, nestfact, contrasts) { ## run cst1way on every levels of the nesting factor(s) # in case other factors are not named, collapse over these ANOPAmessage("Not yet programmed...") } # ################################################################ # # Sub-functions to get observed and expected proportions # # ################################################################ # the null hypothesis for the conditions implicated in the contrast # ns is a vector contrastNull <- function(contrast, ns) { } # the contrast hypothesis for the conditions implicated in the contrast # ns is a vector contrastObsd <- function(contrast, ns) { }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-contrastProportions.R
################################################################################### #' @name conversion #' #' @title Converting between formats #' #' @aliases toWide toLong toCompiled #' #' @md #' #' @description The functions 'toWide()', 'toLong()', and 'toCompiled()' #' converts the data into various formats. #' #' @usage toWide(w) #' @usage toLong(w) #' @usage toCompiled(w) #' #' @param w An instance of an ANOPA object. #' #' @return A data frame in the requested format. #' #' @details The proportions of success of a set of _n_ participants can be #' given using many formats. In what follows, _n_ is the number of #' participants, _p_ is the number of between-subject factor(s), #' $q$ is the number of repeated-measure factor(s). #' * One basic format, called `wide`, has one line per #' participants, with a 1 if a "success" is observed #' or a 0 if no success is observed. What a succes is #' is entirely arbitrary. The proportion of success is then #' the number of 1s divided by the number of participants in each group. #' The data frame has $n$ lines and $p+q$ columns. #' * A second format, called `long`, has, on a line, the #' factor name(s) and 1s or 0s to indicate success or not. #' The data fame has $n x q$ lines and #' 4 columns (a Id column to identify the particpant; $p$ columns #' to identify the groups, one column to identify which whitin-subject #' measure is given and finally, a 1 or 0 for the score of that measurement. #' * A third format, called `compiled`, is to have a list of all #' the between-subject factors and the number of #' success and the total number of participants. #' This format is more compact as if there are 6 groups, #' the data are all contained in six lines (one line per group). #' This format however is only valid for between-subject design as #' we cannot infer the correlation between successes/failure. #' #' @details See the vignette [DataFormatsForProportions](../articles/B-DataFormatsForProportions.html) #' for more. #' #' @examples #' #' # The minimalBSExample contains $n$ of 175 participants categorized according #' # to one factor $f = 1$, namely `State of residency` (with three levels) #' # for 3 possible cells. #' minimalBSExample #' #' # Lets incorporate the data in an ANOPA data structure #' w <- anopa( {s;n} ~ state, minimalBSExample ) #' #' # The data presented using various formats looks like #' toWide(w) #' # ... has 175 lines, one per participants ($n$) and 2 columns (state, success or failure) #' #' toLong(w) #' # ... has 175 lines ($n x f$) and 4 columns (participant's `Id`, state name, measure name, #' # and success or failure) #' #' toCompiled(w) #' # ... has 3 lines and 3 columns ($f$ + 2: number of succes and number of participants). #' #' #' # This second example is from a mixed-design. It indicates the #' # state of a machine, grouped in three categories (the sole between-subject #' # factor) and at four different moments. #' # The four measurements times are before treatment, post-treatment, #' # 1 week later, and finally, 5 weeks later. #' minimalMxExample #' #' # Lets incorporate the data in an ANOPA data structure #' w <- anopa( cbind(bpre,bpost,b1week,b5week) ~ Status, #' minimalMxExample, #' WSFactors = "Moment(4)" ) #' #' # -- Wide format -- #' # Wide format is actually the format of minimalMxExample #' # (27 lines with 8 subjects in the first group and 9 in the second) #' toWide(w) #' #' # -- Long format -- #' # (27 times 4 lines = 108 lines, 4 columns, that is Id, group, measurement, success or failure) #' toLong(w) #' #' # -- Compiled format -- #' # (three lines as there are three groups, 7 columns, that is, #' # the group, the 4 measurements, the number of particpants, and the #' # correlation between measurements for each group measured by unitary alphas) #' toCompiled(w) #' #' ################################################################################### #' #' @importFrom stats reshape #' @export toWide #' @export toLong #' @export toCompiled # ################################################################################### toWide <- function( w = NULL ) { # is w of class ANOPA.object? if (!("ANOPAobject" %in% class(w) )) stop("ANOPA::error(101): argument is not an ANOPA generated object. Exiting...") return( w$wideData ) # nothing to do, the data are internally stored in wide format } toLong <- function( w = NULL ) { # is w of class ANOPA.object? if (!("ANOPAobject" %in% class(w) )) stop("ANOPA::error(102): argument is not an ANOPA generated object. Exiting...") return( wtol(w$wideData, w$DVvariables) ) } toCompiled <- function( w = NULL ) { # is w of class ANOPA.object? if (!("ANOPAobject" %in% class(w) )) stop("ANOPA::error(104): argument is not an ANOPA generated object. Exiting...") return( wtoc(w$wideData, w$DVvariables, "Count" ) ) } ################################################################################### ### UTILITES ################################################################################### # relative complement of x within universal set U complement <- function(U, x) {U[is.na(pmatch(U,x))]} colSums = function (x) { # the equivalent of colMeans for sum if (is.vector(x)) sum(x) else if (is.matrix(x)) apply(x, 2, sum) else if (is.data.frame(x)) apply(x, 2, sum) else "what the fuck??" } ################################################################################### ### CONVERSIONS from wide to ... ################################################################################### # wide => compiled: DONE # ss: all the column names of repeated measures # n: a novel name to contain the total number of observation per cell # for WS design, it adds the unitary Alpha to the groups. wtoc <- function(d, ss, n) { factors <- names(d)[!(names(d) %in% ss )] if (length(factors)==0) { # add a dummy BS factor d[["dummyBSfactor"]] <- 1 factors = "dummyBSfactor" } res <- plyr::ddply(d, factors, function(x) colSums(x[ss])) res[[n]] <- plyr::ddply(d, factors, function(x) dim(x[ss])[1])$V1 names(res)[names(res)=="V1"] <- n if (length(ss)>1) { # adds correlation with unitaryAlpha res[["uAlpha"]] <- plyr::ddply(d, factors, function(x) {unitaryAlpha(as.matrix(x[ss]))} )$V1 names(res)[names(res)=="V1"]="uAlpha" } # remove the dummy factor if needed res[["dummyBSfactor"]] <- NULL return(res) } # wide => long: DONE # ss: all the column names of repeated measures # the columns Id and Variables will be added wtol <- function(d, ss ) { res <- reshape(d, idvar = "Id", varying = ss, v.names = "Value", times = ss, timevar = "Variable", direction = "long" ) # move Id as first column Ids <- res$Id res$Id <- NULL res <- cbind(Id = Ids, res) # sort by Ids res <- res[order(res$Id),] return(res) } ################################################################################### ### CONVERSIONS from compiled to ... ################################################################################### # compiled => wide: DONE possible iif no repeated measures # ss: the repeated measures (should be of length 1) # n: the total number of observations per cell ctow <- function(d, ss, n) { if (length(ss)>1) stop("ANOPA::error(99): internal error. Exiting...") y <- d[,!(names(d)%in%c(ss,n)), drop=FALSE] res <- as.data.frame(lapply(y, rep, d[[n]])) for (i in ss) { res[[i]] <- c(unlist(mapply( \(s,n) c(rep(1,s),rep(0,n-s)), d[[i]], d[[n]] ))) } return(res) } # compiled => long: DONE ctol <- function( d, ss, n ) { tmp <- ctow(d, ss, n) res <- wtol(tmp, ss ) return(res) } ################################################################################### ### CONVERSIONS from long to ... ################################################################################### # long => wide DONE # idcol: name of participant identifier # condcol: the column containing the measure's name # scol: column containing the success ltow <- function(d, idcol, condcol, scol ){ res <- reshape(d, idvar = idcol, timevar = condcol, v.names = scol, direction = "wide") res$Id <- NULL names(res) <- gsub("Value.","", names(res) ) return(res) } # long => compiled DONE ltoc <- function(d, idcol, condcol, scol, n) { t1 <- ltow(d, idcol, condcol, scol ) ss <- unique(d[[condcol]]) res <- wtoc(t1, ss, n) return(res) } ################################################################################### ### DONE... ###################################################################################
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-convert.R
###################################################################################### #' @title emProportions: simple effect analysis of proportions. #' #' @md #' #' @description The function 'emProportions()' performs a _simple effect_ analyses #' of proportions after an omnibus analysis has been obtained with 'anopa()' #' according to the ANOPA framework. Alternatively, it is also called an #' _expected marginal_ analysis of proportions. See \insertCite{lc23b;textual}{ANOPA} for more. #' #' @usage emProportions(w, formula) #' #' @param w An ANOPA object obtained from `anopa()`; #' #' @param formula A formula which indicates what simple effect to analyze. #' Only one simple effect formula at a time can be analyzed. The formula #' is given using a vertical bar, e.g., " ~ factorA | factorB " to obtain #' the effect of Factor A within every level of the Factor B. #' #' @return An ANOPA table of the various simple main effets and if relevant, #' of the simple interaction effets. #' #' @details `emProportions()` computes expected marginal proportions and #' analyzes the hypothesis of equal proportion. #' The sum of the _F_s of the simple effects are equal to the #' interaction and main effect _F_s, as this is an additive decomposition #' of the effects. #' #' @references #' \insertAllCited{} #' #' @examples #' #' # -- FIRST EXAMPLE -- #' # This is a basic example using a two-factors design with the factors between #' # subjects. Ficticious data present the number of success according #' # to Class (three levels) and Difficulty (two levels) for 6 possible cells #' # and 72 observations in total (equal cell sizes of 12 participants in each group). #' twoWayExample #' #' # As seen the data are provided in a compiled format (one line per group). #' # Performs the omnibus analysis first (mandatory): #' w <- anopa( {success;total} ~ Difficulty * Class, twoWayExample) #' summary(w) #' #' # The results shows an important interaction. You can visualize the data #' # using anopaPlot: #' anopaPlot(w) #' # The interaction is overadditive, with a small differences between Difficulty #' # levels in the first class, but important differences between Difficulty for #' # the last class. #' #' # Let's execute the simple effect of Difficulty for every levels of Class #' e <- emProportions(w, ~ Difficulty | Class ) #' summary(e) #' #' #' # -- SECOND EXAMPLE -- #' # Example using the Arrington et al. (2002) data, a 3 x 4 x 2 design involving #' # Location (3 levels), Trophism (4 levels) and Diel (2 levels), all between subject. #' ArringtonEtAl2002 #' #' # first, we perform the omnibus analysis (mandatory): #' w <- anopa( {s;n} ~ Location * Trophism * Diel, ArringtonEtAl2002) #' summary(w) #' #' # There is a near-significant interaction of Trophism * Diel (if we consider #' # the unadjusted p value, but you really should consider the adjusted p value...). #' # If you generate the plot of the four factors, we don't see much: #' anopaPlot(w) #' #' #... but a plot specifically of the interaction helps: #' anopaPlot(w, ~ Trophism * Diel ) #' # it seems that the most important difference is for omnivorous fishes #' # (keep in mind that there were missing cells that were imputed but there does not #' # exist to our knowledge agreed-upon common practices on how to impute proportions... #' # Are you looking for a thesis topic?). #' #' # Let's analyse the simple effect of Trophism for every levels of Diel and Location #' e <- emProportions(w, ~ Trophism | Diel ) #' summary(e) #' #' #' # You can ask easier outputs with #' corrected(w) # or summary(w) for the ANOPA table only #' explain(w) # human-readable ouptut ((pending)) #' ###################################################################################### #' #' @export emProportions # ###################################################################################### emProportions <- function( w = NULL, formula = NULL ){ ############################################################################## ## STEP 1: VALIDATION OF INPUT ############################################################################## # 1.1 Is w of the right type and having more than 1 factor if (!("ANOPAobject" %in% class(w))) stop("ANOPA::error(21): The argument w is not an ANOPA object. Exiting...") if (length( c(w$BSfactColumns, w$WSfactColumns) )==1) stop("ANOPA::error(22): There must be at least two factors in the design. Exiting...") # 1.2 If formula indeed a formula if (!(is.formula(formula))) stop("ANOPA::error(23): The formula argument is not a legitimate formula. Exiting...") # 1.3 Is the rhs having a | sign, and only one if (!(has.nested.terms(formula))) stop("ANOPA::error(24): The rhs of formula must have a variable nested within another variable. Exiting... ") if (length(tmp <- sub.formulas(formula, "|"))!=1) stop("ANOPA::error(25): The rhs of formula must contain a single nested equation. Exiting...") if (tmp[[1]][[2]]==tmp[[1]][[3]]) stop("ANOPA::error(26): The variables on either side of | must differ. Exiting...") # 1.4 If the dependent variable is named (optional), is it the correct variable if (length(formula)==3) { if (formula[[2]] != w$formula[[2]]) stop("ANOPA::error(27): The lhs of formula is not the correct proportion variable. Exiting...") } # 1.5 Are the factors named in formula present in w vars <- all.vars(formula) # extract variables in cbind and with | alike if (!(all(vars %in% names(w$compData)))) stop("ANOPA::error(28): variables in `formula` are not all in the data. Exiting...") ############################################################################## ## STEP 2: Run the analysis based on the number of factors ############################################################################## # 2.1: identify the factors subfactors <- all.vars(tmp[[1]][[2]]) nestfactor <- all.vars(tmp[[1]][[3]]) ANOPAmessage("Not yet programmed...") return(-99) # 2.2: perform the analysis based on the number of factors analysis <- switch( length(subfactors), emf1way(w, subfactors, nestfactor), emf2way(w, subfactors, nestfactor), emf3way(w, subfactors, nestfactor), ) ############################################################################## # STEP 3: Return the object ############################################################################## # 3.1: preserve everything in an object of class ANOPAobject res <- list( type = "ANOPAsimpleeffects", formula = as.formula(w$formula), compiledData = w$compiledData, freqColumn = w$freqColumn, factColumns = w$factColumns, nlevels = w$nlevels, clevels = w$clevels, # new information added formulasimple = as.formula(formula), nestedFactors = nestfactor, subFactors = subfactors, nestedLevels = dim(analysis)[1], results = analysis ) class(res) <- c("ANOPAobject", class(res) ) return( res ) } ########################################## # # # ██╗ ██╗███████╗██████╗ ███████╗ # # ██║ ██║██╔════╝██╔══██╗██╔════╝ # # ███████║█████╗ ██████╔╝█████╗ # # ██╔══██║██╔══╝ ██╔══██╗██╔══╝ # # ██║ ██║███████╗██║ ██║███████╗ # # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ # # # ########################################## # Coding marginal-proportion effects # # is postponed until interest is shown. # ########################################## emf1way <- function(w, subfact, nestfact){ ## Herein, the sole factor analyzed is called factor A, which is nested within factor B, ## that is, the effect of A within b1, the effect of A within b2, ... A within bj. ## There can only be a single nesting variable (e.g., B) ## We can get here if (a) there are 2 factors, (b) there are 3 factors, (c) there are 4 factors # The factors position in the factor list and their number of levels # posB <- (1:length(w$factColumns))[w$factColumns==nestfact] # B <- w$nlevels[posB] # the total n and the vector marginals # First, we compute the expected proportions separately for each levels of factor B # Second, we get the G statistics for each level # Third, the correction factor (Williams, 1976) for each # Finally, getting the p-values for each corrected effect # This is it! let's put the results in a table } emf2way <- function(w, subfacts, nestfact){ ## Herein, the factors decomposed are called factors A*B, ## that is, the effects of (A, B, A*B) within c1, the effects of (A, B, A*B) within c2, etc. ## We can get here if (a) there are 3 factors, (b) there are 4 factors. # The factor positions in the factor list and their number of levels # posC <- (1:length(w$factColumns))[w$factColumns==nestfact] # C <- w$nlevels[posC] # the total n and the matrix marginals # First, we compute the expected proportions e separately for each levels of factor C # Second, we get the G statistics for each level # Third, the correction factor (Williams, 1976) for each # Finally, getting the p-values for each corrected effect # This is it! let's put the results in a table } emf3way <- function(w, subfacts, nestfact){ ## Herein, the factor decomposed is called factor D, ## that is, the effect of (A, B, C, AB, AC, BC, A*B*C) within d1, ## the effect of (A, B, C, AB, AC, BC, A*B*C) within d2, etc. ## There is only one way to get here: a 4 factor design is decomposed. "If you need this functionality, please contact the author...\n" }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-emProportions.R
################################################################################### #' @title transformation functions #' #' @aliases A varA Atrans SE.Atrans var.Atrans CI.Atrans prop CI.prop #' #' @md #' #' @description The transformation functions 'A()' performs the #' Anscombe transformation on a pair \{number of success; number #' of trials\} = \{s; n\} (where the symbol ";" is to be read "over". #' The function 'varA()' returns the theoretical variance from #' the pair \{s; n\}. Both functions are central to the ANOPA #' \insertCite{lc23}{ANOPA}. It was originally proposed by #' \insertCite{z35}{ANOPA} and formalized by \insertCite{a48}{ANOPA}. #' #' @usage A(s, n) #' @usage varA(s, n) #' @usage Atrans(v) #' @usage SE.Atrans(v) #' @usage var.Atrans(v) #' @usage CI.Atrans(v, gamma) #' @usage prop(v) #' @usage CI.prop(v, gamma) #' #' #' @param s a number of success; #' @param n a number of trials. #' @param v a vector of 0s and 1s. #' @param gamma a confidence level, default to .95 when omitted. #' #' #' @return `A()` returns a score between 0 and 1.57 where a `s` of zero results in #' `A(0,n)` tending to zero when the number of trials is large, #' and where the maximum occurs when `s` equals `n` and #' are both very large, so that for example `A(1000,1000) = 1.55`. The #' midpoint is always 0.786 irrespective of the number of trials #' `A(0.5 * n, n) = 0.786`. #' The function `varA()` returns the theoretical variance of an Anscombe #' transformed score. It is exact as `n` gets large, and overestimate variance #' when `n` is small. Therefore, a test based on this transform is either exact #' or conservative. #' @details The functions `A()` and `varA()` take as input two integers, `s` #' the number of success and `n` the number of observations. #' The functions `Atrans()`, `SE.Atrans()`, `var.Atrans()`, `CI.Atrans()`, `prop()` and `CI.prop()` #' take as input a single vector `v` of 0s and 1s from which the number of #' success and the number of observations are derived. #' #' @references #' \insertAllCited #' #' @examples #' # The transformations from number of 1s and total number of observations: #' A(5, 10) #' #' varA(5, 10) #' #' # Same with a vector of observations: #' Atrans( c(1,1,1,1,1,0,0,0,0,0) ) #' #' var.Atrans( c(1,1,1,1,1,0,0,0,0,0) ) #' #' ################################################################################### #' #' @importFrom stats qchisq #' @export A #' @export varA #' @export Atrans #' @export SE.Atrans #' @export var.Atrans #' @export CI.Atrans #' @export prop #' @export CI.prop #' ################################################################################### ################################################################################### # the Anscombe transformation on s, n A <-function(s, n) { asin(sqrt( (s+3/8) / (n+3/4) )) } # ... and its theoretical variance varA <- function(s, n) { 1/ (4*(n+1/2)) } ################################################################################### # the Anscombe transformation for a vector of binary data 0|1 Atrans <-function(v) { x <- sum(v) n <- length(v) asin(sqrt( (x+3/8) / (n+3/4) )) } # its standard error... SE.Atrans <- function(v) { 0.5 / sqrt(length(v)+1/2) } # its variance... var.Atrans <- function(v) { 1 / (4*(length(v)+1/2)) } # ... and its confidence interval CI.Atrans <- function(v, gamma = 0.95){ SE.Atrans(v) * sqrt( stats::qchisq(gamma, df=1) ) } ################################################################################### # the proportion of success for a vector of binary data 0|1 prop <- function(v){ x <- sum(v) n <- length(v) x/n } # the error bar is an inverse transformation of the Anscombe error bars CI.prop <- function(v, gamma = 0.95) { y <- Atrans(v) n <- length(v) cilen <- CI.Atrans(v, gamma) # the difference adjustment is done herein. ylo <- max( y - sqrt(2) * cilen, 0) yhi <- min( y + sqrt(2) * cilen, pi/2) # reverse arc-sin transformation xlo <- (n+3/4)*(sin(ylo)^2) - 3/8 xhi <- (n+3/4)*(sin(yhi)^2) - 3/8 # superb is running automatic checks for values outside valid range if (is.na(xlo)) xlo <- 0.0 if (is.na(xhi)) xhi <- 1.0 cilenlo <- xlo / n cilenhi <- xhi / n c(cilenlo, cilenhi) } ###################################################################################
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-functions.R
#################################################################################### ## @name logicalfunctions ## ## @title logical functions for formulas ## ## @aliases is.formula is.one.sided has.nested.terms has.cbind.terms in.formula sub.formulas ## ## @md ## ## @description The functions 'is.formula()', 'is.one.sided()', ## 'has.nested.terms()', ## 'has.cbind.terms()', 'in.formula()' and 'sub.formulas()' ## performs checks or extract sub-formulas from a given formula. ##s ## @usage is.formula(frm) ## @usage is.one.sided(frm) ## @usage has.nested.terms(frm) ## @usage has.cbind.terms(frm) ## @usage in.formula(frm, whatsym) ## @usage sub.formulas(frm, head) ## ## @param frm a formula; ## @param whatsym a symbol to search in the formula; ## @param head the beginning of a sub-formula to extract ## ## @return `is.formula(frm)`, `has.nested.terms(frm)`, and `has.cbind.terms(frm)` ## returns TRUE if frm is a formula, contains a '|' or a 'cbind' respectively; ## `in.formula(frm, whatsym)` returns TRUE if the symbol `whatsym` is somewhere in 'frm'; ## `sub.formulas(frm, head)` returns a list of all the sub-formulas which contains `head`. ## ## @details These functions are for internal use only. ## ## @examples ## is.formula( success ~ Difficulty ) ## ## has.nested.terms( Level ~ Factor | Level ) ## ## has.cbind.terms( cbind(succ1, succ2, succ3) ~ Difficulty ) ## ## in.formula( success ~ Difficulty, "Difficulty" ) ## ## sub.formulas( cbind(succ1, succ2, succ3) ~ Difficulty, "cbind" ) ## ## ################################################################################## ## ## @export is.formula ## @export is.one.sided ## @export has.nested.terms ## @export has.cbind.terms ## @export in.formula ## @export sub.formulas ## ################################################################################### ################################################################################# # logical functions: ################################################################################# is.formula <- function( frm ) inherits( frm, "formula") is.one.sided <- function( frm ) is.formula(frm) && length(frm) == 2 has.nested.terms <- function( frm ) { if(!is.formula(frm)) return(FALSE) return ( in.formula(frm, "|")) } has.cbind.terms <- function( frm ) { if(!is.formula(frm)) return(FALSE) return ( in.formula(frm, "cbind")) } # performs a depth-first search in the language structure. in.formula <- function( frm, whatsym) { if ((is.symbol(frm))&&(frm == whatsym)) return(TRUE) if (!is.symbol(frm)) { for (i in (1:length(frm)) ) { if (in.formula( frm[[i]], whatsym) ) return(TRUE) } } return(FALSE) } ## Lists all the locations of head of a subformula in formula sub.formulas <- function( frm, head ) { if (!in.formula( frm, head)) stop("error! head not in frm") res <- rrapply::rrapply( frm, condition = function(x) x == head, f = function(x, .xpos) .xpos, how = "flatten" ) # grab the terms, removing last index to have the subformula lapply(res, function(i) frm[[i[1:(length(i)-1)]]]) }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-logicals.R
############################################################################## # DEFINITIONS of the three display methods: # print: The usual, show everything # summarize (or summary): provides a human-readable output of the analysis table # explain : provides all sorts of information regarding the computations ############################################################################## # # As a reminder, the ANOPAobject has all these keys # type : "ANOPAomnibus" or "ANOPAsimpleeffects" # formula : The formula given to anopa # BSfactColumns : Between factor column names # BSfactNlevels : number of levels for each between factor, # WSfactColumns : Within factor column names, # WSfactDesign : how the columns are assigned to a level of the within factors, # WSfactNlevels : number of levels for each within factor, # DVvariables : The dependent variable(s), # wideData : Wide data are needed for plots to compute correlations # compData : Compiled data are used for analyzes # omnibus : Results of the omnibus analysis # ############################################################################## #' #' @title explain #' @name explain #' #' @md #' #' @description #' 'explain()' provides a human-readable, exhaustive, description of #' the results. It also provides references to the key results. #' #' @usage explain(object, ...) #' #' @param object an object to explain #' @param ... ignored #' @return a human-readable output with details of computations. #' #' @export explain <- function(object, ...) { UseMethod("explain") } #' @export explain.default <- function(object, ...) { print(object) } #' @title summarize #' @name summarize #' #' @md #' #' @description 'summarize()' provides the statistics table an ANOPAobject. #' It is synonym of 'summary()' (but as actions are verbs, I used a verb). #' #' @param object an object to summarize #' @param ... ignored #' @return an ANOPA table as per articles. #' #' @export summarize <- function(object, ...) { UseMethod("summarize") } #' @method summarize default #' @export summarize.default <- function(object, ...) { print(object$results, ...) } #' @export summary.ANOPAobject <- function(object, ...) { summarize(object, ...) } ############################################################################## ## ## Implementation of the three methods ## ############################################################################## #' @method print ANOPAobject #' @export print.ANOPAobject <- function(x, ...) { ANOPAmessage("ANOPA completed! My first advise is to use anopaPlot() now. \nUse summary() or summarize() to obtain the ANOPA table.") y <- unclass(x) class(y) <- "list" print(y, digits = 5) return(invisible(x)) } #' @method print ANOPAtable #' @export print.ANOPAtable <- function(x, ...) { r <- x class(r) <- "data.frame" print( as.matrix(round(r, getOption("ANOPA.digits")+2), digits = getOption("ANOPA.digits"), scientific = FALSE ), na.print="", quote = FALSE ) } #' @method summarize ANOPAobject #' @export summarize.ANOPAobject <- function(object, ...) { if (length(object$omnibus) == 1) print(object$omnibus) else { u <- object$omnibus class(u) <- c("ANOPAtable", class(u)) } return(u) } #' @method explain ANOPAobject #' @export explain.ANOPAobject <- function(object, ...) { print("method explain not yet done...") return(invisible(object)) } #' @title corrected #' @name corrected #' #' @md #' #' @description #' 'corrected()' provides an ANOPA table with only the corrected #' statistics. #' #' @usage corrected(object, ...) #' @param object an object to explain #' @param ... ignored #' #' @return An ANOPA table with the corrected test statistics. #' #' @export corrected <- function(object, ...) { UseMethod("corrected") } #' @export corrected.default <- function(object, ...) { print(object) } #' @export corrected.ANOPAobject <- function(object, ...) { if (length(object$omnibus) == 1) print(object$omnibus) else { u <- object$omnibus[,c(1,2,3,5,6,7)] class(u) <- c("ANOPAtable", class(u)) } return(u) } #' @title uncorrected #' @name uncorrected #' #' @md #' #' @description #' 'uncorrected()' provides an ANOPA table with only the uncorrected #' statistics. #' #' @usage uncorrected(object, ...) #' @param object an object to explain #' @param ... ignored #' #' @return An ANOPA table with the un-corrected test statistics. #' That should be avoided, more so if your sample is rather small. #' #' @export uncorrected <- function(object, ...) { UseMethod("uncorrected") } #' @export uncorrected.default <- function(object, ...) { print(object) } #' @export uncorrected.ANOPAobject <- function(object, ...) { if (length(object$omnibus) == 1) print(object$omnibus) else { u <- object$omnibus[,c(1,2,3,4)] class(u) <- c("ANOPAtable", class(u)) } return(u) }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-methods.R
############################################################################## #' @details ANOPA library for analyses of proportions using Anscombe transform #' #' @md #' #' @description 'ANOPA' is a library to perform proportion analyses. #' It is based on the F statistics (first developed by Fisher). #' This statistics is fully additive and can be decomposed in #' main effects and interaction effects, in simple effects in the #' decomposition of a significant interaction, in contrasts, etc. #' The present library performs these analyses and also can be used #' to plan statistical power for the analysis of proportions, obtain #' plots of the various effects, etc. It aims at replicating the most #' commonly-used ANOVA commands so that using this package should be #' easy. #' #' The data supplied to an ANOPA can be in three formats: (i) long format, #' (ii) wide format, (iii) compiled format, or (iv) raw format. Check #' the 'anopa' commands for more precision (in what follow, we assume #' the compiled format where the proportions are given in a column name 'Freq') #' #' The main function is #' #' \code{w <- anopa(formula, data)} #' #' where \code{formula} is a formula giving the factors, e.g., "Freq ~ A * B". #' #' For more details on the underlying math, see \insertCite{lc23;textual}{ANOPA}. #' #' An omnibus analysis may be followed by simple effects or contrasts analyses: #' \code{emProportions(w, formula)} #' \code{contrast(w, listOfContrasts)} #' #' As usual, the output can be obtained with #' \code{print(w) #implicite} #' \code{summary(w) # or summarize(w) for the G statistics table} #' \code{explain(w) # for human-readable output} #' #' Data format can be converted to other format with #' \code{toLong(w)} #' \code{toWide(w)} #' \code{toCompiled(w) # the only format that cannot be used as input to anopa} #' #' The package includes additional, helper, functions: \itemize{ #' \item{\code{anopaPower2N()}} to compute sample size given effect size; #' \item{\code{anopaN2Power()}} to compute statistical power given a sample size; #' \item{\code{anopaPropTofsq()}} to compute the effect size; #' \item{\code{anopaPlot()}} to obtain a plot of the proportions with error bars; #' \item{\code{GRP()}} to generate random proportions from a given design. #' } #' and example datasets, some described in the article: \itemize{ #' \item{\code{ArringtonEtAl2002}} illustrates a 3 x 2 x 4 design; #' \item{\code{ArticleExample1}} illustrates a 4-way design; #' \item{\code{ArticleExample2}} illustrates a 2 x 3 design; #' \item{\code{ArticleExample3}} illustrates a (4) within-subject design; #' } #' #' The functions uses the following options: \itemize{ #' \item{\code{ANOPA.feedback}} 'design', 'warnings', 'summary', 'all' or 'none'; #' \item{\code{ANOPA.zeros}} how are handled the zero trials to avoid 0 divided by 0 error; #' \item{\code{ANOPA.digits}} for the number of digits displayed in the summary table. #' } #' #' @references #' \insertAllCited{} #' ############################################################################## #' @keywords internal "_PACKAGE" #> [1] "_PACKAGE" ############################################################################## # Create a local environment for one temporary variable... ANOPA.env <- new.env(parent = emptyenv()) .onLoad <- function(libname, pkgname) { # Set the default feedback messages displayed and the number of digits: # You can use 'all' to see all the messages, or 'none'. # Also set the replacement if a between-subject cell is missing. options( ANOPA.feedback = c('design','warnings','summary'), ANOPA.digits = 4, ANOPA.zeros = c(0.05, 1) # a very small number of success onto a single try ) } .onDetach <- function(libpath) { # remove the options options( ANOPA.feedback = NULL, ANOPA.digits = NULL, ANOPA.zeros = NULL ) } # display or not stuff # warnings shows warning messages # design shows fyi messages regarding how the design is understood # summary is not used so far... ANOPAwarning <- function( txt ) { if ( ("all" %in% getOption("ANOPA.feedback"))|("warnings" %in% getOption("ANOPA.feedback"))) { warning(txt, call. = FALSE) } } ANOPAmessage <- function( txt ) { if ( ("all" %in% getOption("ANOPA.feedback"))|("design" %in% getOption("ANOPA.feedback"))) { message(txt) } } ############################################################################## # to inhibit "no visible binding for global variable" errors from : # globalVariables(c("xxx","xxx","xxx")) ##############################################################################
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-package.R
###################################################################################### #' @title anopaPlot: Easy plotting of proportions. #' #' @aliases anopaPlot #' #' @md #' #' @description The function 'anopaPlot()' performs a plot of proportions for designs #' with up to 4 factors according to the #' 'ANOPA' framework. See \insertCite{lc23;textual}{ANOPA} for more. The plot is #' realized using the 'suberb' library; see \insertCite{cgh21;textual}{ANOPA}. #' It uses the arc-sine transformation 'A()'. #' #' #' @usage anopaPlot(w, formula, confidenceLevel = .95, allowImputing = FALSE, #' showPlotOnly = TRUE, plotStyle = "line", #' errorbarParams = list( width =0.5, linewidth=0.75 ), ...) #' #' #' @param w An ANOPA object obtained with `anopa()`; #' #' #' @param formula (optional) Use formula to plot just specific terms of the omnibus test. #' For example, if your analysis stored in `w` has factors A, B and C, then #' `anopaPlot(w, ~ A * B)` will only plot the factors A and B. #' @param confidenceLevel Provide the confidence level for the confidence intervals #' (default is 0.95, i.e., 95%). #' @param allowImputing (default FALSE) if there are cells with no observations, can they be #' imputed? If imputed, the option "ANOPA.zeros" will be used to determine #' how many additional observations to add, and with how many successes. #' If for example, the option is (by default) `c(0.05, 1)`, then #' 20 cases will be added, only one being a success (respecting the .05 target). #' _Keep in mind that imputations has never been studies with regards to proportions #' so be mindfull that the default optin has never been tested nor validated._ #' @param showPlotOnly (optional, default True) shows only the plot or else #' shows the numbers needed to make the plot yourself. #' @param plotStyle (optional; default "line") How to plot the proportions; #' see superb for other layouts (e.g., "line"). #' @param errorbarParams (optional; default list( width =0.5, linewidth=0.75 ) ) is #' a list of attributes used to plot the error bars. See superb for more. #' @param ... Other directives sent to superb(), typically 'plotStyle', #' 'errorbarParams', etc. #' #' #' @return a ggplot2 object of the given proportions. #' #' #' @details The plot shows the proportions on the vertical axis as a #' function of the factors (the first on the horizontal axis, the second #' if any in a legend; and if a third or even a fourth factors are present, #' as distinct rows and columns). It also shows 95% confidence intervals of #' the proportions, adjusted for between-cells comparisons. #' The confidence intervals are based on a z distribution, which is adequate #' for large samples \insertCite{c90,ll90}{ANOPA}. This "stand-alone" confidence #' interval is then adjusted for between-cell comparisons using the _superb_ #' framework \insertCite{cgh21}{ANOPA}. #' #' See the vignette [`DataFormatsForProportions`](../articles/B-DataFormatsForProportions.html) #' for more on data formats and how to write their formula. #' See the vignette [`ConfidenceIntervals`](../articles/C-ConfidenceIntervals.html) for #' details on the adjustment and its purpose. #' #' @references #' \insertAllCited{} #' #' @examples #' # #' # The Arrington Et Al., 2002, data on fishes' stomach #' ArringtonEtAl2002 #' #' # This examine the omnibus analysis, that is, a 3 x 2 x 4 ANOPA: #' w <- anopa( {s;n} ~ Location * Trophism * Diel, ArringtonEtAl2002) #' #' # Once processed into w, we can ask for a standard plot #' anopaPlot(w) #' #' # As you may notice, there are points missing because the data have #' # three missing cells. The litterature is not clear what should be #' # done with missing cells. In this package, we propose to impute #' # the missing cells based on the option `getOption("ANOPA.zeros")`. #' # Consider this option with care. #' anopaPlot(w, allowImputing = TRUE) #' #' # We can place the factor `Diel` on the x-axis (first): #' \donttest{anopaPlot(w, ~ Diel * Trophism * Location )} #' #' # Change the style for a plot with bars instead of lines #' \donttest{anopaPlot(w, plotStyle = "bar")} #' #' # Changing the error bar style #' \donttest{anopaPlot(w, plotStyle = "bar", errorbarParams = list( width =0.1, linewidth=0.1 ) )} #' #' # Illustrating the main effect of Location (not interacting with other factors) #' # and the interaction Diel * Trophism separately #' \donttest{anopaPlot(w, ~ Location ) } #' \donttest{anopaPlot(w, ~ Diel * Trophism ) } #' #' # All these plots are ggplot2 so they can be followed with additional directives, e.g. #' library(ggplot2) #' anopaPlot(w, ~ Location) + ylim(0.0, 1.0) + theme_classic() #' anopaPlot(w, ~ Diel * Trophism) + ylim(0.0, 1.0) + theme_classic() #' #' # etc. Any ggplot2 directive can be added to customize the plot to your liking. #' # See the vignette `ArringtonExample`. #' ###################################################################################### #' #' @importFrom Rdpack reprompt #' @importFrom stats aggregate #' @export anopaPlot # ###################################################################################### ################################################################ # create a custom scale based on the arcsin transform # ################################################################ # This scale is adapted to handle cases where numbers outside of # the legitimate scale would be submitted. This happens with # difference-adjusted CI whose length are increased by sqrt(2). # This is tricky because ggplots send extreme cases to the # function to know how to draw it, including NAs. anopa_asn_trans1 <- function(x) { w <- suppressWarnings(asin(sqrt(x))) if (!is.na(x)&&(x<0)) w = anopa_asn_trans1(0) ## boundary truncation if (!is.na(x)&&(x>1)) w = anopa_asn_trans1(1) ## boundary truncation return(w) } anopa_asn_trans2 <- function(x) { w <- suppressWarnings(sin(x)^2) return(w) } anopa_asn_trans <- function () { scales::trans_new("asn2", function(x) { sapply(x, anopa_asn_trans1) }, function(x) { sapply(x, anopa_asn_trans2) }, domain = c(0, 1) ) } ################################################################ # This is it! let's make the plot # ################################################################ # make the plot: just a proxy for suberbPlot anopaPlot <- function(w, formula = NULL, confidenceLevel = 0.95, allowImputing = FALSE, showPlotOnly = TRUE, plotStyle = "line", # lines by default errorbarParams = list( width =0.5, linewidth=0.75 ), # thicker error bars ... # will be transmitted to superb as is ){ ############################################################################## ## STEP 1: validating the formula if one is given ############################################################################## if (!is.null(formula)) { # 1.1. is it a legitimate formula? if (!(is.formula(formula))) stop("ANOPA::error(211): The formula argument is not a legitimate formula. Exiting...") # 1.2. only lhs part if ( !(is.one.sided(formula))) stop("ANOPA::error(212): Only one-sided, rhs, formulas can be given. Exiting...") # 1.3. No cbind, no nested if ((has.nested.terms(formula))||has.cbind.terms(formula)) stop("ANOPA::error(213): No cbind nor nested variables allowed. Exiting...") # 1.4. Are they existing factors? if (!all(all.vars(formula) %in% c(w$BSfactColumns,w$WSfactColumns))) stop("ANOPA::error(214): The named factor(s) given in the formula are not in the model. Exiting...") # 1.6. if everything ok, let's extract the variables... facts <- all.vars(formula)[ !(all.vars(formula) %in% w$DVvariables)] bsfact <- all.vars(formula)[ all.vars(formula) %in% w$BSfactColumns] wsfact <- all.vars(formula)[ all.vars(formula) %in% w$WSfactColumns] # 1.7. ... and aggregate the data accordingly ldata <- wtol( w$wideData, w$DVvariables ) Ainv <- function(a, n) (n+3/4)*(sin(a))^2 - 3/8 Amean <- function(v) Ainv( Atrans(v), 1) if(length(wsfact)>0){ toto <- "Variable" tempvars <- as.character(w$DVvariables) } else { toto <- "dummy" ldata$dummy <- "s" tempvars <- "s" } # merge the within-subject variables to the long data frame if ( length(wsfact) != 0 ) { ldata <- merge(ldata, w$WSfactDesign, by = "Variable", all.x = TRUE) } adata <- stats::aggregate(as.formula( paste("Value", paste( c("Id", toto, facts), collapse="+"), sep="~") ), data = ldata, Amean) #remove the within-subject variables adata[,wsfact] <- NULL wdata <- ltow( adata, "Id", toto, "Value" ) } else { facts <- c(w$BSfactColumns, w$WSfactColumns) bsfact <- w$BSfactColumns wsfact <- w$WSfactColumns wdata <- w$wideData tempvars <- w$DVvariables } # 1.8. If incorrect confidence level... if ((confidenceLevel >= 1)||(confidenceLevel <=0.0)) stop("ANOPA::error(214): The confidence level is not within 0 and 1 (i.e., within 0% and 100%). Exiting...") # 1.9. Empty is not NULL if (length(bsfact)==0) bsfact = NULL if (length(wsfact)==0) { wsfact = NULL } else { wsfact = paste(w$WSfactColumn[w$WSfactColumn %in% wsfact], "(", w$WSfactNlevels[w$WSfactColumn %in% wsfact], ")", sep="") } ############################################################################## ## Step 2: Verify missing data? ############################################################################## # partial observations are not preserved above if the zeros are smaller than 1. if (allowImputing) { missing <- addmissingcellsBSFactors(wdata, bsfact, tempvars) wdata <- rbind(wdata, missing) } ############################################################################## ## All done! ask for the plot or the data ############################################################################## # quiet superb's information opt <- getOption("superb.feedback") on.exit(options(opt)) options(superb.feedback = 'none') if (showPlotOnly) { # generate the plot res <- superb::superbPlot( wdata, BSFactors = bsfact, WSFactors = wsfact, factorOrder = facts, variables = tempvars, statistic = "prop", # the summary statistics defined above errorbar = "CI", # its precision define above gamma = confidenceLevel, adjustment = list( # purpose = "difference", # difference-adjusted CI done in CI.prop decorrelation = if(length(tempvars)>1) "UA" else "none" ), # the following is for the look of the plot plotStyle = plotStyle, errorbarParams = errorbarParams, ... ## passed as is to superb ) + ggplot2::ylab("Proportion") + # use if you want the stretching visible ggplot2::scale_y_continuous(trans=anopa_asn_trans(), breaks = scales::breaks_pretty(n = 10)) } else { # only compute the summary statistics res <- superb::superbData( wdata, BSFactors = bsfact, WSFactors = wsfact, variables = tempvars, statistic = "prop", # the summary statistics defined above errorbar = "CI", # its precision define above gamma = confidenceLevel, adjustment = list( # purpose = "difference", # difference-adjusted CI done in CI.prop decorrelation = if(length(tempvars)>1) "UA" else "none" ) )#$summaryStatistics } # restore superb's information: done with on.exit() # options(superb.feedback = opt) return(res) } addmissingcellsBSFactors <- function( wData, BSFactors, ss) { # List the possible cells to see if some are missing... # The missing cells are added explicitely to the data # There ought to be better code... Sorry about this. toAdd <- wData[1,][-1,] # an empty line repl <- unlist(options("ANOPA.zeros")) repl <- repl/repl[1] if (length(BSFactors) == 2) { for (i in unique(wData[[BSFactors[[1]]]]) ) for (j in unique(wData[[BSFactors[[2]]]]) ) if (!any((wData[[BSFactors[[1]]]] == i)&(wData[[BSFactors[[2]]]] == j))){ ANOPAwarning(paste("ANOPA::warning(201): Cells", i, j, "missing in data. Imputing...")) vide <- wData[1,][-1,] line <- wData[1,] # an empty line for (l in 1:repl[2]) { line[[BSFactors[[1]]]] <- i line[[BSFactors[2]]] <- j for ( m in ss ) {line[[m]]<- if(l <= repl[1]) 1 else 0} vide <- rbind( vide, line ) } toAdd <- rbind(toAdd, vide) } } else if (length(BSFactors) == 3) { for (i in unique(wData[[BSFactors[[1]]]]) ) for (j in unique(wData[[BSFactors[[2]]]]) ) for (k in unique(wData[[BSFactors[[3]]]])) if (!any((wData[[BSFactors[[1]]]] == i)&(wData[[BSFactors[[2]]]] == j)&(wData[[BSFactors[[3]]]] == k))){ ANOPAwarning(paste("ANOPA::warning(201): Cell",i, j, k, "missing in data. Imputing...")) vide <- wData[1,][-1,] line <- wData[1,] # an empty line for (l in 1:repl[2]) { line[[BSFactors[[1]]]] <- i line[[BSFactors[2]]] <- j line[[BSFactors[3]]] <- k for ( m in ss ) {line[[m]] <- if(l <= repl[1]) 1 else 0} vide <- rbind( vide, line ) } toAdd <- rbind(toAdd, vide) } } return( toAdd ) }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-plot.R
###################################################################################### #' @title posthocProportions: post-hoc analysis of proportions. #' #' @md #' #' @description The function 'posthocProportions()' performs post-hoc analyses #' of proportions after an omnibus analysis has been obtained with 'anopa()' #' according to the ANOPA framework. It is based on the tukey HSD test. #' See \insertCite{lc23b;textual}{ANOPA} for more. #' #' @usage posthocProportions(w, formula) #' #' @param w An ANOPA object obtained from `anopa()`; #' #' @param formula A formula which indicates what post-hocs to analyze. #' only one simple effect formula at a time can be analyzed. The formula #' is given using a vertical bar, e.g., " ~ factorA | factorB " to obtain #' the effect of Factor A within every level of the Factor B. #' #' @return a model fit of the simple effect. #' #' @details `posthocProportions()` computes expected marginal proportions and #' analyzes the hypothesis of equal proportion. #' The sum of the $F$s of the simple effects are equal to the #' interaction and main effect $F$s, as this is an additive decomposition #' of the effects. #' #' @references #' \insertAllCited{} #' #' @examples #' #' # -- FIRST EXAMPLE -- #' # This is a basic example using a two-factors design with the factors between #' # subjects. Ficticious data present the number of success according #' # to Class (three levels) and Difficulty (two levels) for 6 possible cells #' # and 72 observations in total (equal cell sizes of 12 participants in each group). #' twoWayExample #' #' # As seen the data are provided in a compiled format (one line per group). #' # Performs the omnibus analysis first (mandatory): #' w <- anopa( {success;total} ~ Class * Difficulty, twoWayExample) #' summary(w) #' #' # The results shows an important interaction. You can visualize the data #' # using anopaPlot: #' anopaPlot(w) #' # The interaction is overadditive, with a small differences between Difficulty #' # levels in the first class, but important differences between Difficulty for #' # the last class. #' #' # Let's execute the post-hoc tests #' e <- posthocProportions(w, ~ Difficulty | Class ) #' summary(e) #' #' #' # -- SECOND EXAMPLE -- #' # Example using the Arrington et al. (2002) data, a 3 x 4 x 2 design involving #' # Location (3 levels), Trophism (4 levels) and Diel (2 levels), all between subject. #' ArringtonEtAl2002 #' #' # first, we perform the omnibus analysis (mandatory): #' w <- anopa( {s;n} ~ Location * Trophism * Diel, ArringtonEtAl2002) #' summary(w) #' #' # There is a near-significant interaction of Trophism * Diel (if we consider #' # the unadjusted p value, but you really should consider the adjusted p value...). #' # If you generate the plot of the four factors, we don't see much: #' # anopaPlot(w) #' #... but with a plot specifically of the interaction helps: #' anopaPlot(w, ~ Trophism * Diel ) #' # it seems that the most important difference is for omnivorous fishes #' # (keep in mind that there were missing cells that were imputed but there does not #' # exist to our knowledge agreed-upon common practices on how to impute proportions... #' # Are you looking for a thesis topic?). #' #' # Let's analyse the simple effect of Tropism for every levels of Diel and Location #' e <- posthocProportions(w, ~ Tropism | Diel ) #' summary(e) #' #' #' # You can ask easier outputs with #' summarize(w) # or summary(w) for the ANOPA table only #' corrected(w) # or uncorrected(w) for an abbreviated ANOPA table #' explain(w) # for a human-readable ouptut ((pending)) #' ###################################################################################### #' #' @export posthocProportions # ###################################################################################### posthocProportions <- function( w = NULL, formula = NULL ){ ANOPAmessage("Not yet programmed...") }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-posthocProportions.R
#################################################################################### #' @title Computing power within the ANOPA. #' #' @aliases anopaPower2N anopaN2Power anopaProp2fsq #' #' @md #' #' @description The function 'anopaN2Power()' performs an analysis of statistical power #' according to the 'ANOPA' framework. See \insertCite{lc23b;textual}{ANOPA} for more. #' 'anopaPower2N()' computes the sample size to reach a given power. #' Finally, 'anopaProp2fsq()' computes the f^2 effect size from a set of proportions. #' #' @usage anopaPower2N(power, P, f2, alpha) #' @usage anopaN2Power(N, P, f2, alpha) #' @usage anopaProp2fsq(props, ns, unitaryAlpha, method="approximation") #' #' @param power target power to attain; #' @param N sample size; #' @param ns sample size per group; #' @param P number of groups; #' @param f2 effect size Cohen's $f^2$; #' @param props a set of expected proportions (if all between 0 and 1) or number of success per group. #' @param alpha (default if omitted .05) the decision threshold. #' @param method for computing effect size $f^2$ is 'approximation' or 'exact' only. #' @param unitaryAlpha for within-subject design, the measure of correlation #' across measurements. #' #' @return `anopaPower2N()` returns a sample size to reach a given power level. #' `anopaN2Power()` returns statistical power from a given sample size. #' `anopaProp2fsq()` returns $f^2$ the effect size from a set of proportions #' and sample sizes. #' #' @details Note that for `anopaProp2fsq()`, the expected effect size $f^2$ #' depends weakly on the sample sizes. Indeed, the Anscombe transform #' can reach more extreme scores when the sample sizes are larger, influencing #' the expected effect size. #' #' @references #' \insertAllCited{} #' #' #' @examples #' # 1- Example of the article: #' # with expected frequences .34 to .16, assuming as a first guess groups of 25 observations: #' f2 <- anopaProp2fsq( c( 0.32, 0.64, 0.40, 0.16), c(25,25,25,25) ); #' f2 #' # f-square is 0.128. #' #' # f-square can be converted to eta-square with #' eta2 <- f2 / (1 + f2) #' #' #' # With a total sample of 97 observations over four groups, #' # statistical power is quite satisfactory (85%). #' anopaN2Power(97, 4, f2) #' #' # 2- Power planning. #' # Suppose we plan a four-classification design with expected proportions of: #' pred <- c(.35, .25, .25, .15) #' # P is the number of classes (here 4) #' P <- length(pred) #' # We compute the predicted f2 as per Eq. 5 #' f2 <- 2 * sum(pred * log(P * pred) ) #' # the result, 0.0822, is a moderate effect size. #' #' # Finally, aiming for a power of 80%, we run #' anopaPower2N(0.80, P, f2) #' # to find that a little more than 132 participants are enough. #' #################################################################################### #' #' @importFrom stats var #' @importFrom stats qchisq #' @importFrom stats optimize #' @export anopaN2Power #' @export anopaPower2N #' @export anopaProp2fsq # #################################################################################### # 1- Returns statistical power given N, P, f2 and alpha anopaN2Power <- function(N, P, f2, alpha = .05) { pFc <- stats::qchisq( p = 1 - alpha, df = P-1 ) 1- stats::pchisq(q = pFc, df = P-1, ncp = N * f2) } # 2- Performs a search for N to reach a certain statistical power anopaPower2N <- function(power, P, f2, alpha = .05) { # define the objective: minimize the lag between the desired power and # the power achieved by a certain N objective <- function(N, power, P, f2, alpha = .05) { (power - anopaN2Power(N, P, f2, alpha))^2 } # launch optimization search for the desired N between 10 and 1000 stats::optimize( objective, interval = c(10,1000), P = P, f2 = f2, power = power)$minimum } # 3- propTof2 computes f^2 from proportions/nbre of success using # approximation of Eq. (17) or exact formula anopaProp2fsq <- function(props, ns, unitaryAlpha = NULL, method = "approximation") { if (is.null(props)) stop("ANOPA::effect size: Empty vector of propoprtions. Exiting...") if (is.null(ns)) stop("ANOPA::effect size: Empty vector of sample sizes. Exiting...") if (length(props)!=length(ns)) stop("ANOPA::effect size: Number of proportions not equalt to number of sample sizes. Exiting...") if (!(method %in% c("approximation","exact")) ) stop("ANOPA::effect size: Methods are 'approximation' or 'exact' only. Exiting...") if (all(props<1)) props = props * ns if (!(is.null(unitaryAlpha))) {if ((unitaryAlpha< -1)|(unitaryAlpha>1)) stop("ANOPA::effect size: unitary Alpha must be between -1 and 1. Exiting...") } if (is.null(unitaryAlpha)) {m = 1} else {m = 1/sqrt(1-unitaryAlpha)} p <- length(props) if (method =="approximation") { return( m^2 * 4 * (p-1)/p * stats::var( mapply(A, props, ns) ) ) } else { return( m^2 * (p-1) * stats::var( mapply(A, props, ns) ) / sum( ns / (4*(ns+1/2))) ) } }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-power.R
###################################################################################### #' @title Generating random proportions with GRP #' #' @aliases GRP rBernoulli gSwitch #' #' @md #' #' @description The function 'GRP()' #' generates random proportions based on a design, i.e., #' a list giving the factors and the categories with each factor. #' The data are returned in the 'wide' format. #' #' @usage GRP( props, n, BSDesign=NULL, WSDesign=NULL, sname = "s" ) #' @usage rBernoulli(n, p) #' #' @param BSDesign A list with the between-subject factor(s) and the categories within each; #' @param WSDesign A list with the within-subject factor(s) and the categories within each; #' @param props (optional) the proportion of succes in each cell of the design. Default 0.50; #' @param sname (optional) the column name that will contain the success/failure; #' @param n How many simulated participants are in each between-subject group (can be a vector, one per group); #' @param p a proportion of success; #' #' @return `GRP()` returns a data frame containing success (coded as 1) or failure (coded as 0) #' for n participants per cells of the design. Note that correlated #' scores cannot be generated by `GRP()`; see \insertCite{ld98}{ANOPA}. #' `rBernoulli()` returns a sequence of n success (1) or failures (0) #' #' @details The name of the function `GRP()` is derived from `GRD()`, #' a general-purpose tool to generate random data \insertCite{ch19}{ANOPA} #' now bundled in the `superb` package \insertCite{cgh21}{ANOPA}. #' `GRP()` is actually a proxy for `GRD()`. #' #' @references #' \insertAllCited{} #' #' @examples #' #' # The first example generate scorse for 20 particants in one factor having #' # two categories (low and high): #' design <- list( A=c("low","high")) #' GRP( design, props = c(0.1, 0.9), n = 20 ) #' #' # This example has two factors, with factor A having levels a, b, c #' # and factor B having 2 levels, for a total of 6 conditions; #' # with 40 participants per group, it represents 240 observations: #' design <- list( A=letters[1:3], B = c("low","high")) #' GRP( design, props = c(0.1, 0.15, 0.20, 0.80, 0.85, 0.90), n = 40 ) #' #' # groups can be unequal: #' design <- list( A=c("low","high")) #' GRP( design, props = c(0.1, 0.9), n = c(5, 35) ) #' #' # Finally, repeated-measures can be generated #' # but note that correlated scores cannot be generated with `GRP()` #' wsDesign = list( Moment = c("pre", "post") ) #' GRP( WSDesign=wsDesign, props = c(0.1, 0.9), n = 10 ) #' #' # This last one has three factors, for a total of 3 x 2 x 2 = 12 cells #' design <- list( A=letters[1:3], B = c("low","high"), C = c("cat","dog")) #' GRP( design, n = 30, props = rep(0.5,12) ) #' #' # To specify unequal probabilities, use #' design <- list( A=letters[1:3], B = c("low","high")) #' expProp <- c(.05, .05, .35, .35, .10, .10 ) #' GRP( design, n = 30, props=expProp ) #' #' # The name of the column containing the proportions can be changed #' GRP( design, n=30, props=expProp, sname="patate") #' #' # Examples of use of rBernoulli #' t <- rBernoulli(50, 0.1) #' mean(t) #' #' #' ###################################################################################### #' #' @importFrom superb GRD #' @importFrom stats runif #' @export GRP #' @export rBernoulli # ###################################################################################### # a Bernoulli random success/failure generator rBernoulli <- function(n, p = 0.5) { (stats::runif(n) < p) + 0 #converts to numeric } # `gSwitch()` is a generalized form of switch which can switch based on # an exact match with scalars or with vectors. # @param .default default expression if none of the formulas in ... applies # # Examples of use of gSwitch with a scalar (first) and a 2-dim vector (second) # gSwitch( 12, 10~"a", 11~"b", 12~"c") # gSwitch( c(1,2), c(1,1)~ 11, c(1,2) ~ 12, c(1,3) ~ 13) # # they return "c" and 12 respectively # # # when the right-hand side of equation is an expression, it is evaluated: # v <- "toto" # w <- 4 # gSwitch( c(v,w), # c("toto",4) ~ paste(v,w,sep="<>"), # c("bibi",9) ~ paste(v,w,sep="><") # ) # # Same as switch except that the expression can be a vector # rather than singletons. In that case the whole vector must # match one of the proposed alternative or else .default is returned. # The alternatives are given as formulas of the form: toMatch ~ replacement: gSwitch <- function(EXPR, ..., .default = -99 ){ alt <- list(...) if (!(all(sapply(alt, is.formula)))) stop("ANOPA::GRP: not all alternatives are formulas. Exiting...") if (any(sapply(alt, is.one.sided))) stop("ANOPA::GRP: not all alternatives are two-sided ~. Exiting...") res <- sapply(alt, \(x) identical(eval(x[[2]]), EXPR ) ) pos <- which( TRUE == res ) if (length(pos) == 0) return (eval(.default)) else return(eval(alt[[pos]][[3]])) } # the main function here: Generating Random Proportions # (or more precisely, of success or failure, coded as 1 or 0 resp.) GRP <- function( props, # proportions of success in the population n, # sample size. BSDesign = NULL, # a list of factors with each a vector of levels WSDesign = NULL, # idem sname = "s" # name of the column containing the results 0|1 ) { # 1- Validation of input if (is.null(n)) stop("ANOPA::GRP (1002): The sample size n is not provided. Exiting...") if (is.null(BSDesign)&&is.null(WSDesign)) stop("ANOPA::GRP (1003): Both within subject and between subject factors are null. Provide at least one factor. Exiting...") # preparing the input to match GRD format BSDasText <- mapply(\(x,y) {paste(x,"(",paste(y,collapse=","),")",sep="")}, names(BSDesign), BSDesign ) WSDasText<- mapply(\(x,y) {paste(x,"(",paste(y,collapse=","),")",sep="")}, names(WSDesign), WSDesign ) wholeDesign <- c(BSDesign, WSDesign) ## 2- Expanding the design into cells levels <- sapply(wholeDesign, length, simplify = TRUE) nlevels <- prod(levels) if (length(props)!=nlevels) stop("ANOPA::GRP (1001): The number of proportions given does not match the number of cells in the design. Exiting...") res <- expand.grid(wholeDesign) # 3- Assemble a gSwitch expression fct <- function(line) { paste(" c('",paste(line[(1:length(line)-1)], collapse="','"), "') ~ ", line[length(line)], sep="") } lines <- apply(as.matrix(cbind(res, props)), 1, fct) gswit <- paste("ANOPA:::gSwitch( c(",paste(names(res), collapse=","), "), \n", paste(lines, collapse=",\n"), ",\n .default = -99\n)", sep="") # 4- All done! send this to GRD superb::GRD( SubjectsPerGroup= n, BSFactors = BSDasText, WSFactors = WSDasText, RenameDV = sname, Population = list( scores = paste("rBernoulli(1, p=",gswit,")") ) ) }
/scratch/gouwar.j/cran-all/cranData/ANOPA/R/ANOPA-random.R