46 Commits
Author SHA1 Message Date
dr. M.S. (Matthijs) Berends fbd5d32541 small fixes 2022-08-29 09:35:36 +02:00
dr. M.S. (Matthijs) Berends e7af5fc716 fix AMR vignette 2022-08-28 22:38:08 +02:00
Dr. Matthijs Berends e975a3043c New tibbles, cleanup
New tibbles, cleanup
2022-08-28 21:52:45 +02:00
dr. M.S. (Matthijs) Berends 2ed5f13880 Fixes #57 2022-08-28 21:13:26 +02:00
dr. M.S. (Matthijs) Berends 1e4eaf23f2 unit tests 2022-08-28 20:49:04 +02:00
dr. M.S. (Matthijs) Berends 21b4552f5a unit test fix 2022-08-28 20:10:05 +02:00
dr. M.S. (Matthijs) Berends c44ddf272f fix for R <= 3.3 2022-08-28 19:34:04 +02:00
dr. M.S. (Matthijs) Berends 71db246d5c unit test fix 2022-08-28 19:17:12 +02:00
Dr. Matthijs Berends 0d67db4f32 Update check.yaml 2022-08-28 16:03:23 +02:00
Dr. Matthijs Berends 95f9563f58 Update check.yaml 2022-08-28 13:42:16 +02:00
Dr. Matthijs Berends 1a9bac8c64 Update check.yaml 2022-08-28 13:32:26 +02:00
Dr. Matthijs Berends 40d9658e06 Update check.yaml 2022-08-28 11:22:40 +02:00
dr. M.S. (Matthijs) Berends f781998904 amoxicillin interpretation fix 2022-08-28 11:17:53 +02:00
dr. M.S. (Matthijs) Berends 4d050aef7c styled, unit test fix 2022-08-28 10:31:50 +02:00
dr. M.S. (Matthijs) Berends 4cb1db4554 data export 2022-08-27 20:51:26 +02:00
dr. M.S. (Matthijs) Berends 303d61b473 new tibble export 2022-08-27 20:49:37 +02:00
dr. M.S. (Matthijs) Berends 164886f50b new workflow files 2022-08-26 23:25:37 +02:00
dr. M.S. (Matthijs) Berends 3cef2ea286 restore LFS 2022-08-26 23:21:31 +02:00
dr. M.S. (Matthijs) Berends 3864ab2fb8 Feather and Parquet files 2022-08-26 22:25:15 +02:00
dr. M.S. (Matthijs) Berends 4da32e3d40 set up Git LFS for large files 2022-08-26 14:02:08 +02:00
dr. M.S. (Matthijs) Berends e05d0365a9 website update 2022-08-25 19:19:16 +02:00
dr. M.S. (Matthijs) Berends 5501cffbb0 website update 2022-08-25 19:18:48 +02:00
dr. M.S. (Matthijs) Berends d3000a9492 website update 2022-08-25 19:16:16 +02:00
dr. M.S. (Matthijs) Berends 2cbce2cefa website update 2022-08-25 19:14:07 +02:00
dr. M.S. (Matthijs) Berends 53c4b37252 website update 2022-08-25 19:11:02 +02:00
dr. M.S. (Matthijs) Berends bdbc112f99 website update 2022-08-21 17:22:34 +02:00
dr. M.S. (Matthijs) Berends d6676e9443 disk documentation fix 2022-08-21 16:52:09 +02:00
dr. M.S. (Matthijs) Berends 952d16de33 new, automated website 2022-08-21 16:37:20 +02:00
dr. M.S. (Matthijs) Berends 7226b70c3d update languages 2022-08-20 20:17:14 +02:00
dr. M.S. (Matthijs) Berends 3f2f60ab77 language updates 2022-08-19 12:33:14 +02:00
Anton Mymrikov 4b19c3dc5e Add Ukrainian translation (#67) 2022-08-18 11:29:18 +02:00
dr. M.S. (Matthijs) Berends ab97268f4c (v1.8.1.9014) add Toxoplasma 2022-08-12 23:27:15 +02:00
dr. M.S. (Matthijs) Berends 7f981e7778 (v1.8.1.9013) add Toxoplasma 2022-06-10 13:15:23 +02:00
dr. M.S. (Matthijs) Berends b84d647cac (v1.8.1.9012) update prevalence of some genera 2022-06-03 13:28:55 +02:00
dr. M.S. (Matthijs) Berends 1b84564d36 (v1.8.1.9011) update prevalence of some genera 2022-06-03 12:43:25 +02:00
dr. M.S. (Matthijs) Berends 70a07bad39 (v1.8.1.9010) random when pkg not loaded 2022-05-16 12:52:50 +02:00
dr. M.S. (Matthijs) Berends 2c5bc73ed6 (v1.8.1.9009) random when pkg not loaded 2022-05-16 09:29:46 +02:00
dr. M.S. (Matthijs) Berends 58ed15e7ac (v1.8.1.9008) website update 2022-05-11 10:26:58 +02:00
dr. M.S. (Matthijs) Berends 6de5375256 (v1.8.1.9007) website update 2022-05-11 10:10:31 +02:00
dr. M.S. (Matthijs) Berends 859224e9d0 (v1.8.1.9006) added EUCAST 2022 and CLSI 2022 2022-05-10 21:34:30 +02:00
dr. M.S. (Matthijs) Berends 680e8e7a41 (v1.8.1.9005) as.rsi() fix for EUCAST 2022-05-10 17:01:37 +02:00
dr. M.S. (Matthijs) Berends d4e22069bc (v1.8.1.9004) fix for table() on MICs 2022-05-09 21:33:27 +02:00
dr. M.S. (Matthijs) Berends 1c891cc90c (v1.8.1.9003) set_mo_source() fix 2022-05-09 20:36:44 +02:00
dr. M.S. (Matthijs) Berends 152db9d1b5 (v1.8.1.9002) fix for table() on MICs 2022-05-09 17:08:40 +02:00
dr. M.S. (Matthijs) Berends 4754848e96 (v1.8.1.9001) update unit tests, fixes #53 2022-04-08 11:02:45 +02:00
dr. M.S. (Matthijs) Berends 641b88c814 website update 2022-03-27 09:37:55 +02:00
475 changed files with 37157 additions and 68871 deletions
+11 -9
View File
@@ -23,14 +23,16 @@
^data-raw$
^\.lintr$
^tests/testthat/_snaps$
^vignettes/AMR.Rmd$
^vignettes/benchmarks.Rmd$
^vignettes/datasets.Rmd$
^vignettes/EUCAST.Rmd$
^vignettes/MDR.Rmd$
^vignettes/PCA.Rmd$
^vignettes/resistance_predict.Rmd$
^vignettes/SPSS.Rmd$
^vignettes/WHONET.Rmd$
^vignettes/AMR\.Rmd$
^vignettes/AMR_intro\.png$
^vignettes/benchmarks\.Rmd$
^vignettes/benchmarks\.Rmd\.not$
^vignettes/datasets\.Rmd$
^vignettes/EUCAST\.Rmd$
^vignettes/MDR\.Rmd$
^vignettes/PCA\.Rmd$
^vignettes/resistance_predict\.Rmd$
^vignettes/SPSS\.Rmd$
^vignettes/WHONET\.Rmd$
^logo.svg$
^CRAN-SUBMISSION$
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
echo "Running pre-commit hook..."
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if command -v Rscript > /dev/null; then
if [ "$(Rscript -e 'cat(all(c('"'pkgload'"', '"'devtools'"', '"'dplyr'"', '"'styler'"') %in% rownames(installed.packages())))')" = "TRUE" ]; then
Rscript -e "source('data-raw/_pre_commit_hook.R')"
currentpkg=`Rscript -e "cat(pkgload::pkg_name())"`
echo "-> Adding all files in folders 'data-raw', 'inst', 'man', and 'R' to this git commit"
git add data-raw/*
git add inst/*
git add man/*
git add R/*
else
echo "- R package 'pkgload', 'devtools', 'dplyr', or 'styler' not installed!"
currentpkg="your"
fi
else
echo "- R is not available on your system!"
currentpkg="your"
fi
echo ""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
echo ">> Updating semantic versioning and date..."
# get tags from remote, and remove tags not on remote:
git fetch origin --prune --prune-tags --quiet
currenttagfull=`git describe --tags --abbrev=0`
currenttag=`git describe --tags --abbrev=0 | sed 's/v//'`
if [ "$currenttag" = "" ]; then
# there is no tag, so set tag to 0.0.1 and commit index to current count
echo ">> - no git tags found, create one in this format: 'v(x).(y).(z)'!"
currenttag="0.0.1"
currentcommit=`git rev-list --count HEAD`
else
# there is a tag, so base version number on that
currentcommit=`git rev-list --count ${currenttagfull}..HEAD`
if (( "$currentcommit" == 0 )); then
# tag is new, so this must become the version number
currentversion="$currenttag"
fi
echo ">> - latest tag is '${currenttagfull}', with ${currentcommit} previous commits"
fi
if [ "$currentversion" = "" ]; then
# combine tag (e.g. 1.2.3) and commit number (like 5) increased by 9000 to indicate beta version
currentversion="$currenttag.$((currentcommit + 9001))" # results in e.g. 1.2.3.9005
fi
echo ">> - ${currentpkg} pkg version set to ${currentversion}"
# set version number and date to DESCRIPTION file
sed -i -- "s/^Version: .*/Version: ${currentversion}/" DESCRIPTION
sed -i -- "s/^Date: .*/Date: $(date '+%Y-%m-%d')/" DESCRIPTION
echo ">> - updated DESCRIPTION"
# remove leftover on macOS
rm -f DESCRIPTION--
# add to commit
git add DESCRIPTION
# set version number to NEWS file
if [ -e "NEWS.md" ]; then
if [ "$currentpkg" = "your" ]; then
currentpkg=""
fi
sed -i -- "1s/.*/# ${currentpkg} ${currentversion}/" NEWS.md
echo ">> - updated NEWS.md"
# remove leftover on macOS
rm -f NEWS.md--
# add to commit
git add NEWS.md
else
echo ">> - no NEWS.md found!"
fi
echo ">> "
+81
View File
@@ -0,0 +1,81 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
on:
pull_request:
# run in each PR in this repo
branches: '**'
name: R-code-check-PR
jobs:
R-code-check-PR:
# do not run if we are the authors - the other checks will already run
if: ${{ github.event.comment.author_association != 'MEMBER' && github.event.comment.author_association != 'OWNER' }}
runs-on: ${{ matrix.config.os }}
continue-on-error: ${{ matrix.config.allowfail }}
name: ${{ matrix.config.os }} (R-${{ matrix.config.r }})
strategy:
fail-fast: false
matrix:
config:
- {os: macOS-latest, r: 'devel', allowfail: true}
- {os: macOS-latest, r: 'release', allowfail: false}
- {os: ubuntu-latest, r: 'devel', allowfail: true}
- {os: ubuntu-latest, r: 'release', allowfail: false}
- {os: windows-latest, r: 'devel', allowfail: true}
- {os: windows-latest, r: 'release', allowfail: false}
env:
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
R_KEEP_PKG_SOURCE: yes
steps:
- uses: actions/checkout@v3
- uses: r-lib/actions/setup-pandoc@v2
- uses: r-lib/actions/setup-r@v2
with:
r-version: ${{ matrix.config.r }}
# use RStudio Package Manager to quickly install packages
use-public-rspm: true
- uses: r-lib/actions/setup-r-dependencies@v2
with:
extra-packages: any::rcmdcheck
needs: check
- uses: r-lib/actions/check-r-package@v2
env:
_R_CHECK_LENGTH_1_CONDITION_: verbose
_R_CHECK_LENGTH_1_LOGIC2_: verbose
# during 'R CMD check', R_LIBS_USER will be overwritten, so:
R_LIBS_USER_GH_ACTIONS: ${{ env.R_LIBS_USER }}
R_RUN_TINYTEST: true
+37 -42
View File
@@ -25,12 +25,8 @@
on:
push:
branches:
- development
- main
pull_request:
branches:
- main
# run after a git push on any branch in this repo
branches: '**'
schedule:
# run a schedule everyday at 1 AM.
# this is to check that all dependencies are still available (see R/zzz.R)
@@ -52,42 +48,33 @@ jobs:
config:
# test all systems against all released versions of R >= 3.0, we support them all!
- {os: macOS-latest, r: 'devel', allowfail: true}
- {os: macOS-latest, r: '4.2', allowfail: false}
- {os: macOS-latest, r: '4.1', allowfail: false}
- {os: macOS-latest, r: '4.0', allowfail: false}
- {os: macOS-latest, r: '3.6', allowfail: false}
- {os: macOS-latest, r: '3.5', allowfail: false}
- {os: macOS-latest, r: '3.4', allowfail: false}
- {os: macOS-latest, r: '3.3', allowfail: false}
- {os: macOS-latest, r: '3.2', allowfail: false}
# - {os: macOS-latest, r: '3.1', allowfail: true}
# - {os: macOS-latest, r: '3.0', allowfail: true}
- {os: ubuntu-20.04, r: 'devel', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '4.1', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '4.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.6', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.5', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.4', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.3', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.2', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.1', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: '3.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-22.04, r: 'devel', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '4.2', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '4.1', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '4.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.6', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.5', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.4', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.3', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.2', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.1', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: ubuntu-22.04, r: '3.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/jammy/latest"}
- {os: windows-latest, r: 'devel', allowfail: true}
- {os: windows-latest, r: '4.2', allowfail: false}
- {os: windows-latest, r: '4.1', allowfail: false}
- {os: windows-latest, r: '4.0', allowfail: false}
- {os: windows-latest, r: '3.6', allowfail: false}
- {os: windows-latest, r: '3.5', allowfail: false}
- {os: windows-latest, r: '3.4', allowfail: false}
- {os: windows-latest, r: '3.3', allowfail: false}
# - {os: windows-latest, r: '3.2', allowfail: true}
# - {os: windows-latest, r: '3.1', allowfail: true}
# - {os: windows-latest, r: '3.0', allowfail: true}
env:
R_REMOTES_NO_ERRORS_FROM_WARNINGS: true
RSPM: ${{ matrix.config.rspm }}
R_REPOSITORIES: "https://cran.rstudio.com"
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: r-lib/actions/setup-r@v2
with:
@@ -99,9 +86,9 @@ jobs:
if: runner.os == 'Linux'
# update the below with sysreqs::sysreqs("DESCRIPTION") and check the "DEB" entries (for Ubuntu).
# we don't want to depend on the sysreqs pkg here, as it requires quite a recent R version
# as of May 2021: https://sysreqs.r-hub.io/pkg/AMR,R,cleaner,curl,dplyr,ggplot2,ggtext,knitr,microbenchmark,pillar,readxl,rmarkdown,rstudioapi,rvest,skimr,tidyr,tinytest,xml2,backports,crayon,rlang,vctrs,evaluate,highr,markdown,stringr,yaml,xfun,cli,ellipsis,fansi,lifecycle,utf8,glue,mime,magrittr,stringi,generics,R6,tibble,tidyselect,pkgconfig,purrr,digest,gtable,isoband,MASS,mgcv,scales,withr,nlme,Matrix,farver,labeling,munsell,RColorBrewer,viridisLite,lattice,colorspace,gridtext,Rcpp,RCurl,png,jpeg,bitops,cellranger,progress,rematch,hms,prettyunits,htmltools,jsonlite,tinytex,base64enc,httr,selectr,openssl,askpass,sys,repr,cpp11
# as of May 2021: https://sysreqs.r-hub.io/pkg/AMR,R,cleaner,curl,dplyr,ggplot2,knitr,microbenchmark,pillar,readxl,rmarkdown,rstudioapi,rvest,skimr,tidyr,tinytest,xml2,backports,crayon,rlang,vctrs,evaluate,highr,markdown,stringr,yaml,xfun,cli,ellipsis,fansi,lifecycle,utf8,glue,mime,magrittr,stringi,generics,R6,tibble,tidyselect,pkgconfig,purrr,digest,gtable,isoband,MASS,mgcv,scales,withr,nlme,Matrix,farver,labeling,munsell,RColorBrewer,viridisLite,lattice,colorspace,gridtext,Rcpp,RCurl,png,jpeg,bitops,cellranger,progress,rematch,hms,prettyunits,htmltools,jsonlite,tinytex,base64enc,httr,selectr,openssl,askpass,sys,repr,cpp11
run: |
sudo apt install -y libssl-dev libxml2-dev libicu-dev libcurl4-openssl-dev libpng-dev
sudo apt install -y libssl-dev libxml2-dev libcurl4-openssl-dev
- name: Restore cached R packages
# this step will add the step 'Post Restore cached R packages' on a succesful run
@@ -110,10 +97,9 @@ jobs:
path: ${{ env.R_LIBS_USER }}
key: ${{ matrix.config.os }}-r-${{ matrix.config.r }}-v4
- name: Unpack AMR and install R dependencies
- name: Install R dependencies
if: always()
run: |
tar -xf data-raw/AMR_latest.tar.gz
Rscript -e "source('data-raw/_install_deps.R')"
shell: bash
@@ -126,33 +112,42 @@ jobs:
shell: Rscript {0}
- name: Remove vignettes on R without knitr support
if: matrix.config.r == '3.0' || matrix.config.r == '3.1' || matrix.config.r == '3.2'
# writing to DESCRIPTION2 and then moving to DESCRIPTION is required for R < 3.3 as writeLines() cannot overwrite
if: matrix.config.r == '3.0' || matrix.config.r == '3.1' || matrix.config.r == '3.2' || matrix.config.r == '3.3'
# writing to DESCRIPTION2 and then moving to DESCRIPTION is required for R <= 3.3 as writeLines() cannot overwrite
run: |
rm -rf AMR/vignettes
Rscript -e "writeLines(readLines('AMR/DESCRIPTION')[!grepl('VignetteBuilder', readLines('AMR/DESCRIPTION'))], 'AMR/DESCRIPTION2')"
rm AMR/DESCRIPTION
mv AMR/DESCRIPTION2 AMR/DESCRIPTION
rm -rf vignettes
Rscript -e "writeLines(readLines('DESCRIPTION')[!grepl('VignetteBuilder', readLines('DESCRIPTION'))], 'DESCRIPTION2')"
rm DESCRIPTION
mv DESCRIPTION2 DESCRIPTION
shell: bash
- name: Run R CMD check
if: always()
env:
# see https://rstudio.github.io/r-manuals/r-ints/Tools.html for an overview
_R_CHECK_CRAN_INCOMING_: false
_R_CHECK_FORCE_SUGGESTS_: false
_R_CHECK_DEPENDS_ONLY_: true
_R_CHECK_LENGTH_1_CONDITION_: verbose
_R_CHECK_LENGTH_1_LOGIC2_: verbose
# no check for old R versions - these packages require higher R versions
_R_CHECK_RD_XREFS_: ${{ matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2' && matrix.config.r != '3.3' && matrix.config.r != '3.4' }}
_R_CHECK_FORCE_SUGGESTS_: false
R_CHECK_CONSTANTS: 5
R_JIT_STRATEGY: 3
# during 'R CMD check', R_LIBS_USER will be overwritten, so:
R_LIBS_USER_GH_ACTIONS: ${{ env.R_LIBS_USER }}
# this is a required value to run the unit tests:
R_RUN_TINYTEST: true
run: |
R CMD check --no-manual --run-donttest --run-dontrun AMR
cd ..
R CMD build AMR
R CMD check --as-cran --no-manual --run-donttest --run-dontrun AMR_*.tar.gz
shell: bash
- name: Show unit tests output
if: always()
run: |
cd ../AMR.Rcheck
find . -name 'tinytest.Rout*' -exec cat '{}' \; || true
shell: bash
@@ -161,4 +156,4 @@ jobs:
uses: actions/upload-artifact@v2
with:
name: artifacts-${{ matrix.config.os }}-r${{ matrix.config.r }}
path: AMR.Rcheck
path: ${{ github.workspace }}/AMR.Rcheck
+12 -39
View File
@@ -25,65 +25,38 @@
on:
push:
branches:
- development
- main
branches: '**'
pull_request:
branches:
- main
branches: '**'
name: code-coverage
jobs:
code-coverage:
runs-on: macOS-latest
runs-on: ubuntu-latest
env:
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
CODECOV_TOKEN: ${{secrets.CODECOV_TOKEN}}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: r-lib/actions/setup-pandoc@v2
- uses: r-lib/actions/setup-r@v2
with:
r-version: release
# use RStudio Package Manager to quickly install packages
use-public-rspm: true
- uses: r-lib/actions/setup-pandoc@v2
# with:
# pandoc-version: '2.7.3' # The pandoc version to download (if necessary) and use.
- name: Query dependencies
# this will change once a week, so it will cache dependency updates
run: |
writeLines(paste(format(Sys.Date(), "week %V %Y"), sprintf("R-%i.%i", getRversion()$major, getRversion()$minor)), ".github/week-R-version")
shell: Rscript {0}
- name: Restore cached R packages
# this step will add the step 'Post Restore cached R packages' on a succesful run
uses: actions/cache@v2
- uses: r-lib/actions/setup-r-dependencies@v2
with:
path: ${{ env.R_LIBS_USER }}
key: ${{ matrix.config.os }}-${{ hashFiles('.github/week-R-version') }}-v4
- name: Unpack AMR and install R dependencies
run: |
tar -xf data-raw/AMR_latest.tar.gz
Rscript -e "source('data-raw/_install_deps.R')"
shell: bash
- name: Show session info
run: |
options(width = 100)
utils::sessionInfo()
as.data.frame(utils::installed.packages())[, "Version", drop = FALSE]
shell: Rscript {0}
extra-packages: any::covr
- name: Test coverage
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
R_LIBS_USER_GH_ACTIONS: ${{ env.R_LIBS_USER }}
R_RUN_TINYTEST: true
run: |
install.packages("covr", repos = "https://cran.rstudio.com/")
library(AMR)
library(tinytest)
x <- covr::codecov(line_exclusions = list("R/atc_online.R", "R/mo_source.R", "R/translate.R", "R/resistance_predict.R", "R/aa_helper_functions.R", "R/aa_helper_pm_functions.R", "R/zzz.R"))
print(x)
shell: Rscript {0}
+12 -26
View File
@@ -25,45 +25,31 @@
on:
push:
branches:
- development
- main
branches: '**'
pull_request:
branches:
- main
branches: '**'
name: lintr
jobs:
lintr:
runs-on: macOS-latest
runs-on: ubuntu-latest
env:
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: r-lib/actions/setup-pandoc@v2
- uses: r-lib/actions/setup-r@v2
- name: Query dependencies
run: |
install.packages('remotes')
saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2)
writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version")
shell: Rscript {0}
- name: Cache R packages
uses: actions/cache@v2
with:
path: ${{ env.R_LIBS_USER }}
key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }}
restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-
r-version: release
# use RStudio Package Manager to quickly install packages
use-public-rspm: true
- name: Install dependencies
run: |
install.packages(c("remotes"))
remotes::install_deps(dependencies = TRUE)
remotes::install_cran("lintr")
shell: Rscript {0}
- uses: r-lib/actions/setup-r-dependencies@v2
with:
extra-packages: any::lintr
- name: Lint
run: lintr::lint_package(linters = lintr::with_defaults(line_length_linter = NULL, trailing_whitespace_linter = NULL, object_name_linter = NULL, cyclocomp_linter = NULL, object_length_linter = lintr::object_length_linter(length = 50L)), exclusions = list("R/aa_helper_pm_functions.R"))
+60
View File
@@ -0,0 +1,60 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# Create a website from the R documentation using pkgdown
# Git commit and push to the 'gh-pages' branch
on:
push:
# only on main
branches: 'main'
name: Update website
jobs:
update-website:
runs-on: ubuntu-latest
continue-on-error: true
steps:
# Set up R (current stable version) and developer tools
- uses: actions/checkout@v3
- uses: r-lib/actions/setup-pandoc@v2
- name: Set up R
uses: r-lib/actions/setup-r@v2
with:
r-version: "release"
# use RStudio Package Manager (RSPM) to quickly install packages
use-public-rspm: true
- name: Set up R dependencies
uses: r-lib/actions/setup-r-dependencies@v2
with:
extra-packages: any::pkgdown
# Send updates to repo using GH Actions bot
- name: Create website in separate branch
run: |
git config user.name "github-actions"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
Rscript -e 'pkgdown::deploy_to_branch(new_process = FALSE, clean = TRUE, install = TRUE, branch = "gh-pages")'
-1
View File
@@ -5,7 +5,6 @@ doc
.Rhistory
.RData
.Ruserdata
AMR.Rproj
tests/testthat/Rplots.pdf
inst/doc
/src/*.o
+25
View File
@@ -0,0 +1,25 @@
Version: 1.0
RestoreWorkspace: No
SaveWorkspace: No
AlwaysSaveHistory: Yes
EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8
RnwWeave: Sweave
LaTeX: pdfLaTeX
AutoAppendNewline: Yes
LineEndingConversion: Posix
BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
PackageBuildArgs: --no-build-vignettes
PackageCheckArgs: --no-build-vignettes --as-cran
PackageRoxygenize: rd,collate,namespace
UseNativePipeOperator: No
+23 -64
View File
@@ -1,82 +1,41 @@
Package: AMR
Version: 1.8.1
Date: 2022-03-17
Version: 1.8.1.9046
Date: 2022-08-29
Title: Antimicrobial Resistance Data Analysis
Description: Functions to simplify and standardise antimicrobial resistance (AMR)
data analysis and to work with microbial and antimicrobial properties by
using evidence-based methods and reliable reference data such as LPSN
<doi:10.1099/ijsem.0.004332>.
Authors@R: c(
person(given = c("Matthijs", "S."),
family = "Berends",
email = "m.berends@certe.nl",
role = c("aut", "cre"),
comment = c(ORCID = "0000-0001-7620-1800")),
person(given = c("Christian", "F."),
family = "Luz",
role = c("aut", "ctb"),
comment = c(ORCID = "0000-0001-5809-5995")),
person(given = "Dennis",
family = "Souverein",
role = c("aut", "ctb"),
comment = c(ORCID = "0000-0003-0455-0336")),
person(given = c("Erwin", "E.", "A."),
family = "Hassing",
role = c("aut", "ctb")),
person(given = c("Casper", "J."),
family = "Albers",
role = "ths",
comment = c(ORCID = "0000-0002-9213-6743")),
person(given = c("Judith", "M."),
family = "Fonville",
role = "ctb"),
person(given = c("Alex", "W."),
family = "Friedrich",
role = "ths",
comment = c(ORCID = "0000-0003-4881-038X")),
person(given = "Corinna",
family = "Glasner",
role = "ths",
comment = c(ORCID = "0000-0003-1241-1328")),
person(given = c("Eric", "H.", "L.", "C.", "M."),
family = "Hazenberg",
role = "ctb"),
person(given = "Gwen",
family = "Knight",
role = "ctb",
comment = c(ORCID = "0000-0002-7263-9896")),
person(given = "Annick",
family = "Lenglet",
role = "ctb",
comment = c(ORCID = "0000-0003-2013-8405")),
person(given = c("Bart", "C."),
family = "Meijer",
role = "ctb"),
person(given = "Sofia",
family = "Ny",
role = "ctb",
comment = c(ORCID = "0000-0002-2017-1363")),
person(given = c("Rogier", "P."),
family = "Schade",
role = "ctb"),
person(given = c("Bhanu", "N.", "M."),
family = "Sinha",
role = "ths",
comment = c(ORCID = "0000-0003-1634-0010")),
person(given = "Anthony",
family = "Underwood",
role = "ctb",
comment = c(ORCID = "0000-0002-8547-4277")))
person(family = "Berends", c("Matthijs", "S."), role = c("aut", "cre"), comment = c(ORCID = "0000-0001-7620-1800"), email = "m.berends@certe.nl"),
person(family = "Luz", c("Christian", "F."), role = c("aut", "ctb"), comment = c(ORCID = "0000-0001-5809-5995")),
person(family = "Souverein", c("Dennis"), role = c("aut", "ctb"), comment = c(ORCID = "0000-0003-0455-0336")),
person(family = "Hassing", c("Erwin", "E.", "A."), role = c("aut", "ctb")),
person(family = "Albers", c("Casper", "J."), role = "ths", comment = c(ORCID = "0000-0002-9213-6743")),
person(family = "Dutey-Magni", c("Peter"), role = "ctb", comment = c(ORCID = "0000-0002-8942-9836")),
person(family = "Fonville", c("Judith", "M"), role = "ctb"),
person(family = "Friedrich", c("Alex", "W."), role = "ths", comment = c(ORCID = "0000-0003-4881-038X")),
person(family = "Glasner", c("Corinna"), role = "ths", comment = c(ORCID = "0000-0003-1241-1328")),
person(family = "Hazenberg", c("Eric", "H.", "L.", "C.", "M."), role = "ctb"),
person(family = "Knight", c("Gwen"), role = "ctb", comment = c(ORCID = "0000-0002-7263-9896")),
person(family = "Lenglet", c("Annick"), role = "ctb", comment = c(ORCID = "0000-0003-2013-8405")),
person(family = "Meijer", c("Bart", "C."), role = "ctb"),
person(family = "Mykhailenko", c("Dmytro"), role = "ctb"),
person(family = "Mymrikov", c("Anton"), role = "ctb"),
person(family = "Ny", c("Sofia"), role = "ctb", comment = c(ORCID = "0000-0002-2017-1363")),
person(family = "Schade", c("Rogier", "P."), role = "ctb"),
person(family = "Sinha", c("Bhanu", "N.", "M."), role = "ths", comment = c(ORCID = "0000-0003-1634-0010")),
person(family = "Underwood", c("Anthony"), role = "ctb", comment = c(ORCID = "0000-0002-8547-4277")))
Depends: R (>= 3.0.0)
Enhances:
cleaner,
skimr,
ggplot2,
tibble,
tidyselect
Suggests:
curl,
dplyr,
ggtext,
knitr,
progress,
readxl,
@@ -90,5 +49,5 @@ BugReports: https://github.com/msberends/AMR/issues
License: GPL-2 | file LICENSE
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.1.2
RoxygenNote: 7.2.1
Roxygen: list(markdown = TRUE)
+3 -1
View File
@@ -50,7 +50,6 @@ S3method(any,mic)
S3method(as.data.frame,ab)
S3method(as.data.frame,mo)
S3method(as.double,mic)
S3method(as.integer,mic)
S3method(as.list,custom_eucast_rules)
S3method(as.list,custom_mdro_guideline)
S3method(as.matrix,mic)
@@ -310,6 +309,7 @@ export(quinolones)
export(random_disk)
export(random_mic)
export(random_rsi)
export(reset_AMR_locale)
export(resistance)
export(resistance_predict)
export(right_join_microorganisms)
@@ -318,6 +318,7 @@ export(rsi_predict)
export(scale_rsi_colours)
export(scale_y_percent)
export(semi_join_microorganisms)
export(set_AMR_locale)
export(set_ab_names)
export(set_mo_source)
export(skewness)
@@ -325,6 +326,7 @@ export(streptogramins)
export(susceptibility)
export(tetracyclines)
export(theme_rsi)
export(translate_AMR)
export(trimethoprims)
export(ureidopenicillins)
importFrom(graphics,arrows)
+37 -8
View File
@@ -1,8 +1,37 @@
# AMR 1.8.1.9046
### New
* EUCAST 2022 and CLSI 2022 guidelines have been added for `as.rsi()`. EUCAST 2022 is now the new default guideline for all MIC and disks diffusion interpretations.
* Support for `data.frame`-enhancing R packages, more specifically: `data.table`, `tibble`, and `tsibble`. AMR package functions that have a data set as output (such as `rsi_df()` and `bug_drug_combinations()`), will now return the same data type as the input. Furthermore, all our data sets are now in `tibble` format.
* Our data sets are now also continually exported to Apache Feather and Apache Parquet formats. You can find more info [in this article on our website](https://msberends.github.io/AMR/articles/datasets.html).
* Support for the following languages: Chinese, Greek, Japanese, Polish, Turkish and Ukrainian. We are very grateful for the valuable input by our colleagues from other countries. The `AMR` package is now available in 16 languages.
### Changed
* Fix for using `as.rsi()` on certain EUCAST breakpoints for MIC values
* Fix for using `as.rsi()` on `NA` values (e.g. `as.rsi(as.disk(NA), ...)`)
* Removed `as.integer()` for MIC values, since MIC are not integer values and running `table()` on MIC values consequently failed for not being able to retrieve the level position (as that's how normally `as.integer()` on `factor`s work)
* `droplevels()` on MIC will now return a common `factor` at default and will lose the `<mic>` class. Use `droplevels(..., as.mic = TRUE)` to keep the `<mic>` class.
* Small fix for using `ab_from_text()`
* Fixes for reading in text files using `set_mo_source()`, which now also allows the source file to contain valid taxonomic names instead of only valid microorganism ID of this package
* Using any `random_*()` function (such as `random_mic()`) is now possible by directly calling the package without loading it first: `AMR::random_mic(10)`
* Added *Toxoplasma gondii* (`P_TXPL_GOND`) to the `microorganisms` data set, together with its genus, family, and order
* Changed value in column `prevalence` of the `microorganisms` data set from 3 to 2 for these genera: *Acholeplasma*, *Alistipes*, *Alloprevotella*, *Bergeyella*, *Borrelia*, *Brachyspira*, *Butyricimonas*, *Cetobacterium*, *Chlamydia*, *Chlamydophila*, *Deinococcus*, *Dysgonomonas*, *Elizabethkingia*, *Empedobacter*, *Haloarcula*, *Halobacterium*, *Halococcus*, *Myroides*, *Odoribacter*, *Ornithobacterium*, *Parabacteroides*, *Pedobacter*, *Phocaeicola*, *Porphyromonas*, *Riemerella*, *Sphingobacterium*, *Streptobacillus*, *Tenacibaculum*, *Terrimonas*, *Victivallis*, *Wautersiella*, *Weeksella*
* Fix for using the form `df[carbapenems() == "R", ]` using the latest `vctrs` package
* Fix for using `info = FALSE` in `mdro()`
* All data sets in this package are now exported as `tibble`, instead of base R `data.frame`s. Older R versions are still supported.
* Automatic language determination will give a note once a session
* For all interpretation guidelines using `as.rsi()` on amoxicillin, the rules for ampicillin will be used if amoxicillin rules are not available
* Fix for using `ab_atc()` on non-existing ATC codes
### Other
* New website to make use of the new Bootstrap 5 and pkgdown v2.0. The website now contains results for all examples and will be automatically regenerated with every change to our repository, using GitHub Actions
* Added Peter Dutey-Magni and Anton Mymrikov as contributors, to thank them for their valuable input
* Set up Git Large File Storage (Git LFS) for the large SAS and SPSS file formats
* All R and Rmd files in this project are now styled using the `styler` package
# `AMR` 1.8.1
All functions in this package are considered to be stable. Updates to the AMR interpretation rules (such as by EUCAST and CLSI), the microbial taxonomy, and the antibiotic dosages will all be updated every 6 to 12 months.
### Changed
* Fix for using `as.rsi()` on values containing capped values (such as `>=`), sometimes leading to `NA`
* Support for antibiotic interpretations of the MIPS laboratory system: `"U"` for S ('susceptible urine'), `"D"` for I ('susceptible dose-dependent')
@@ -187,7 +216,7 @@ All functions in this package are considered to be stable. Updates to the AMR in
* Functions `oxazolidinones()` (an antibiotic selector function) and `filter_oxazolidinones()` (an antibiotic filter function) to select/filter on e.g. linezolid and tedizolid
```r
library(dplyr)
x <- example_isolates %>% select(date, hospital_id, oxazolidinones())
x <- example_isolates %>% select(date, ward, oxazolidinones())
#> Selecting oxazolidinones: column 'LNZ' (linezolid)
x <- example_isolates %>% filter_oxazolidinones()
@@ -272,7 +301,7 @@ All functions in this package are considered to be stable. Updates to the AMR in
```r
library(dplyr)
example_isolates %>%
group_by(patient_id, hospital_id) %>%
group_by(patient_id, ward) %>%
filter(is_new_episode(date, episode_days = 60))
```
* Functions `mo_is_gram_negative()` and `mo_is_gram_positive()` as wrappers around `mo_gramstain()`. They always return `TRUE` or `FALSE` (except when the input is `NA` or the MO code is `UNKNOWN`), thus always return `FALSE` for species outside the taxonomic kingdom of Bacteria.
@@ -886,7 +915,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
boxplot()
# grouped boxplots:
septic_patients %>%
group_by(hospital_id) %>%
group_by(ward) %>%
freq(age) %>%
boxplot()
```
@@ -1139,13 +1168,13 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Support for grouping variables, test with:
```r
septic_patients %>%
group_by(hospital_id) %>%
group_by(ward) %>%
freq(gender)
```
* Support for (un)selecting columns:
```r
septic_patients %>%
freq(hospital_id) %>%
freq(ward) %>%
select(-count, -cum_count) # only get item, percent, cum_percent
```
* Check for `hms::is.hms`
+33 -15
View File
@@ -24,34 +24,50 @@
# ==================================================================== #
# add new version numbers here, and add the rules themselves to "data-raw/eucast_rules.tsv" and rsi_translation
# (sourcing "data-raw/_internals.R" will process the TSV file)
EUCAST_VERSION_BREAKPOINTS <- list("11.0" = list(version_txt = "v11.0",
# (sourcing "data-raw/_pre_commit_hook.R" will process the TSV file)
EUCAST_VERSION_BREAKPOINTS <- list(
"11.0" = list(
version_txt = "v11.0",
year = 2021,
title = "'EUCAST Clinical Breakpoint Tables'",
url = "https://www.eucast.org/clinical_breakpoints/"),
"10.0" = list(version_txt = "v10.0",
url = "https://www.eucast.org/clinical_breakpoints/"
),
"10.0" = list(
version_txt = "v10.0",
year = 2020,
title = "'EUCAST Clinical Breakpoint Tables'",
url = "https://www.eucast.org/ast_of_bacteria/previous_versions_of_documents/"))
EUCAST_VERSION_EXPERT_RULES <- list("3.1" = list(version_txt = "v3.1",
url = "https://www.eucast.org/ast_of_bacteria/previous_versions_of_documents/"
)
)
EUCAST_VERSION_EXPERT_RULES <- list(
"3.1" = list(
version_txt = "v3.1",
year = 2016,
title = "'EUCAST Expert Rules, Intrinsic Resistance and Exceptional Phenotypes'",
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"),
"3.2" = list(version_txt = "v3.2",
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"
),
"3.2" = list(
version_txt = "v3.2",
year = 2020,
title = "'EUCAST Expert Rules' and 'EUCAST Intrinsic Resistance and Unusual Phenotypes'",
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"),
"3.3" = list(version_txt = "v3.3",
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"
),
"3.3" = list(
version_txt = "v3.3",
year = 2021,
title = "'EUCAST Expert Rules' and 'EUCAST Intrinsic Resistance and Unusual Phenotypes'",
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"))
url = "https://www.eucast.org/expert_rules_and_expected_phenotypes/"
)
)
SNOMED_VERSION <- list(title = "Public Health Information Network Vocabulary Access and Distribution System (PHIN VADS)",
SNOMED_VERSION <- list(
title = "Public Health Information Network Vocabulary Access and Distribution System (PHIN VADS)",
current_source = "US Edition of SNOMED CT from 1 September 2020",
current_version = 12,
current_oid = "2.16.840.1.114222.4.11.1009",
value_set_name = "Microorganism",
url = "https://phinvads.cdc.gov/vads/ViewValueSet.action?oid=2.16.840.1.114222.4.11.1009")
url = "https://phinvads.cdc.gov/vads/ViewValueSet.action?oid=2.16.840.1.114222.4.11.1009"
)
CATALOGUE_OF_LIFE <- list(
year = 2019,
@@ -61,7 +77,8 @@ CATALOGUE_OF_LIFE <- list(
yearmonth_LPSN = "5 October 2021"
)
globalVariables(c(".rowid",
globalVariables(c(
".rowid",
"ab",
"ab_txt",
"affect_ab_name",
@@ -130,4 +147,5 @@ globalVariables(c(".rowid",
"xvar",
"y",
"year",
"yvar"))
"yvar"
))
+289 -146
View File
@@ -43,11 +43,16 @@ pm_left_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
colnames(x)[int_x] <- paste0(colnames(x)[int_x], suffix[1L])
colnames(y)[int_y] <- paste0(colnames(y)[int_y], suffix[2L])
merged <- cbind(x,
y[match(x[, by[1], drop = TRUE],
y[, by[2], drop = TRUE]),
merged <- cbind(
x,
y[match(
x[, by[1], drop = TRUE],
y[, by[2], drop = TRUE]
),
colnames(y)[!colnames(y) %in% colnames(x) & !colnames(y) == by[2]],
drop = FALSE])
drop = FALSE
]
)
rownames(merged) <- NULL
merged
@@ -73,24 +78,30 @@ where <- function(fn) {
}
# copied and slightly rewritten from poorman under same license (2021-10-15)
quick_case_when <- function (...) {
quick_case_when <- function(...) {
fs <- list(...)
lapply(fs, function(x) if (class(x) != "formula")
stop("`case_when()` requires formula inputs."))
lapply(fs, function(x) {
if (class(x) != "formula") {
stop("`case_when()` requires formula inputs.")
}
})
n <- length(fs)
if (n == 0L)
if (n == 0L) {
stop("No cases provided.")
}
validate_case_when_length <- function (query, value, fs) {
validate_case_when_length <- function(query, value, fs) {
lhs_lengths <- lengths(query)
rhs_lengths <- lengths(value)
all_lengths <- unique(c(lhs_lengths, rhs_lengths))
if (length(all_lengths) <= 1L)
if (length(all_lengths) <= 1L) {
return(all_lengths[[1L]])
}
non_atomic_lengths <- all_lengths[all_lengths != 1L]
len <- non_atomic_lengths[[1L]]
if (length(non_atomic_lengths) == 1L)
if (length(non_atomic_lengths) == 1L) {
return(len)
}
inconsistent_lengths <- non_atomic_lengths[-1L]
lhs_problems <- lhs_lengths %in% inconsistent_lengths
rhs_problems <- rhs_lengths %in% inconsistent_lengths
@@ -99,18 +110,19 @@ quick_case_when <- function (...) {
stop("The following formulas must be length ", len, " or 1, not ",
paste(inconsistent_lengths, collapse = ", "), ".\n ",
paste(fs[problems], collapse = "\n "),
call. = FALSE)
call. = FALSE
)
}
}
replace_with <- function (x, i, val, arg_name) {
if (is.null(val))
replace_with <- function(x, i, val, arg_name) {
if (is.null(val)) {
return(x)
}
i[is.na(i)] <- FALSE
if (length(val) == 1L) {
x[i] <- val
}
else {
} else {
x[i] <- val[i]
}
x
@@ -122,15 +134,18 @@ quick_case_when <- function (...) {
for (i in seq_len(n)) {
query[[i]] <- eval(fs[[i]][[2]], envir = default_env)
value[[i]] <- eval(fs[[i]][[3]], envir = default_env)
if (!is.logical(query[[i]]))
if (!is.logical(query[[i]])) {
stop(fs[[i]][[2]], " does not return a `logical` vector.")
}
}
m <- validate_case_when_length(query, value, fs)
out <- value[[1]][rep(NA_integer_, m)]
replaced <- rep(FALSE, m)
for (i in seq_len(n)) {
out <- replace_with(out, query[[i]] & !replaced, value[[i]],
NULL)
out <- replace_with(
out, query[[i]] & !replaced, value[[i]],
NULL
)
replaced <- replaced | (query[[i]] & !is.na(query[[i]]))
}
out
@@ -162,17 +177,22 @@ addin_insert_like <- function() {
pos_preceded_by <- function(txt) {
if (tryCatch(substr(current_row_txt, current_col - nchar(trimws(txt, which = "right")), current_col) == trimws(txt, which = "right"),
error = function(e) FALSE)) {
error = function(e) FALSE
)) {
return(TRUE)
}
tryCatch(substr(current_row_txt, current_col - nchar(txt), current_col) %like% paste0("^", txt),
error = function(e) FALSE)
error = function(e) FALSE
)
}
replace_pos <- function(old, with) {
modifyRange(document_range(document_position(current_row, current_col - nchar(old)),
document_position(current_row, current_col)),
modifyRange(document_range(
document_position(current_row, current_col - nchar(old)),
document_position(current_row, current_col)
),
text = with,
id = context$id)
id = context$id
)
}
if (pos_preceded_by(" %like% ")) {
@@ -202,33 +222,46 @@ check_dataset_integrity <- function() {
plural <- c(" is", "s", "")
}
if (message_not_thrown_before("check_dataset_integrity", overwritten)) {
warning_("The following data set", plural[1],
warning_(
"The following data set", plural[1],
" overwritten by your global environment and prevent", plural[2],
" the AMR package from working correctly: ",
vector_and(overwritten, quotes = "'"),
".\nPlease rename your object", plural[3], ".")
".\nPlease rename your object", plural[3], "."
)
}
}
# check if other packages did not overwrite our data sets
valid_microorganisms <- TRUE
valid_antibiotics <- TRUE
tryCatch({
valid_microorganisms <- all(c("mo", "fullname", "kingdom", "phylum",
tryCatch(
{
valid_microorganisms <- all(c(
"mo", "fullname", "kingdom", "phylum",
"class", "order", "family", "genus",
"species", "subspecies", "rank",
"species_id", "source", "ref", "prevalence") %in% colnames(microorganisms),
na.rm = TRUE)
valid_antibiotics <- all(c("ab", "atc", "cid", "name", "group",
"species_id", "source", "ref", "prevalence"
) %in% colnames(microorganisms),
na.rm = TRUE
)
valid_antibiotics <- all(c(
"ab", "atc", "cid", "name", "group",
"atc_group1", "atc_group2", "abbreviations",
"synonyms", "oral_ddd", "oral_units",
"iv_ddd", "iv_units", "loinc") %in% colnames(antibiotics),
na.rm = TRUE)
}, error = function(e) {
"iv_ddd", "iv_units", "loinc"
) %in% colnames(antibiotics),
na.rm = TRUE
)
},
error = function(e) {
# package not yet loaded
require("AMR")
})
stop_if(!valid_microorganisms | !valid_antibiotics,
"the data set `microorganisms` or `antibiotics` was overwritten in your environment because another package with the same object name(s) was loaded _after_ the AMR package, preventing the AMR package from working correctly. Please load the AMR package last.")
}
)
stop_if(
!valid_microorganisms | !valid_antibiotics,
"the data set `microorganisms` or `antibiotics` was overwritten in your environment because another package with the same object name(s) was loaded _after_ the AMR package, preventing the AMR package from working correctly. Please load the AMR package last."
)
invisible(TRUE)
}
@@ -258,7 +291,6 @@ search_type_in_df <- function(x, type, info = TRUE) {
} else if (any(colnames_formatted %like_case% "species")) {
found <- sort(colnames(x)[colnames_formatted %like_case% "species"])
}
}
# -- key antibiotics
if (type %in% c("keyantibiotics", "keyantimicrobials")) {
@@ -272,11 +304,13 @@ search_type_in_df <- function(x, type, info = TRUE) {
# WHONET support
found <- sort(colnames(x)[colnames_formatted %like_case% "^(specimen date|specimen_date|spec_date)"])
if (!any(class(pm_pull(x, found)) %in% c("Date", "POSIXct"))) {
stop(font_red(paste0("Found column '", font_bold(found), "' to be used as input for `col_", type,
"`, but this column contains no valid dates. Transform its values to valid dates first.")),
call. = FALSE)
stop(font_red(paste0(
"Found column '", font_bold(found), "' to be used as input for `col_", type,
"`, but this column contains no valid dates. Transform its values to valid dates first."
)),
call. = FALSE
)
}
} else if (any(vapply(FUN.VALUE = logical(1), x, function(x) inherits(x, c("Date", "POSIXct"))))) {
# take first <Date> column
found <- colnames(x)[vapply(FUN.VALUE = logical(1), x, function(x) inherits(x, c("Date", "POSIXct")))]
@@ -314,7 +348,8 @@ search_type_in_df <- function(x, type, info = TRUE) {
if (!is.logical(x[, found, drop = TRUE])) {
message_("Column '", font_bold(found), "' found as input for `col_", type,
"`, but this column does not contain 'logical' values (TRUE/FALSE) and was ignored.",
add_fn = font_red)
add_fn = font_red
)
found <- NULL
}
}
@@ -335,26 +370,39 @@ search_type_in_df <- function(x, type, info = TRUE) {
}
is_valid_regex <- function(x) {
regex_at_all <- tryCatch(vapply(FUN.VALUE = logical(1),
regex_at_all <- tryCatch(vapply(
FUN.VALUE = logical(1),
X = strsplit(x, ""),
FUN = function(y) any(y %in% c("$", "(", ")", "*", "+", "-",
FUN = function(y) {
any(y %in% c(
"$", "(", ")", "*", "+", "-",
".", "?", "[", "]", "^", "{",
"|", "}", "\\"),
na.rm = TRUE),
USE.NAMES = FALSE),
error = function(e) rep(TRUE, length(x)))
regex_valid <- vapply(FUN.VALUE = logical(1),
"|", "}", "\\"
),
na.rm = TRUE
)
},
USE.NAMES = FALSE
),
error = function(e) rep(TRUE, length(x))
)
regex_valid <- vapply(
FUN.VALUE = logical(1),
X = x,
FUN = function(y) !"try-error" %in% class(try(grepl(y, "", perl = TRUE),
silent = TRUE)),
USE.NAMES = FALSE)
FUN = function(y) {
!"try-error" %in% class(try(grepl(y, "", perl = TRUE),
silent = TRUE
))
},
USE.NAMES = FALSE
)
regex_at_all & regex_valid
}
stop_ifnot_installed <- function(package) {
# no "utils::installed.packages()" since it requires non-staged install since R 3.6.0
# https://developer.r-project.org/Blog/public/2019/02/14/staged-install/index.html
vapply(FUN.VALUE = character(1), package, function(pkg)
vapply(FUN.VALUE = character(1), package, function(pkg) {
tryCatch(get(".packageName", envir = asNamespace(pkg)),
error = function(e) {
if (pkg == "rstudioapi") {
@@ -362,9 +410,12 @@ stop_ifnot_installed <- function(package) {
} else if (pkg != "base") {
stop("This requires the '", pkg, "' package.",
"\nTry to install it with: install.packages(\"", pkg, "\")",
call. = FALSE)
call. = FALSE
)
}
}))
}
)
})
return(invisible())
}
@@ -391,11 +442,13 @@ import_fn <- function(name, pkg, error_on_fail = TRUE) {
if (isTRUE(error_on_fail)) {
stop_("function ", name, "() is not an exported object from package '", pkg,
"'. Please create an issue at https://github.com/msberends/AMR/issues. Many thanks!",
call = FALSE)
call = FALSE
)
} else {
return(NULL)
}
})
}
)
}
# this alternative wrapper to the message(), warning() and stop() functions:
@@ -416,14 +469,17 @@ word_wrap <- function(...,
if (msg %like% "\n") {
# run word_wraps() over every line here, bind them and return again
return(paste0(vapply(FUN.VALUE = character(1),
return(paste0(vapply(
FUN.VALUE = character(1),
trimws(unlist(strsplit(msg, "\n")), which = "right"),
word_wrap,
add_fn = add_fn,
as_note = FALSE,
width = width,
extra_indent = extra_indent),
collapse = "\n"))
extra_indent = extra_indent
),
collapse = "\n"
))
}
# correct for operators (will add the space later on)
@@ -434,10 +490,13 @@ word_wrap <- function(...,
# where are the spaces now?
msg_stripped_wrapped <- paste0(strwrap(msg_stripped,
simplify = TRUE,
width = width),
collapse = "\n")
width = width
),
collapse = "\n"
)
msg_stripped_wrapped <- paste0(unlist(strsplit(msg_stripped_wrapped, "(\n|\\*\\|\\*)")),
collapse = "\n")
collapse = "\n"
)
msg_stripped_spaces <- which(unlist(strsplit(msg_stripped, "")) == " ")
msg_stripped_wrapped_spaces <- which(unlist(strsplit(msg_stripped_wrapped, "")) != "\n")
# so these are the indices of spaces that need to be replaced
@@ -485,8 +544,10 @@ message_ <- function(...,
as_note = TRUE) {
message(word_wrap(...,
add_fn = add_fn,
as_note = as_note),
appendLF = appendLF)
as_note = as_note
),
appendLF = appendLF
)
}
warning_ <- function(...,
@@ -495,9 +556,11 @@ warning_ <- function(...,
call = FALSE) {
warning(word_wrap(...,
add_fn = add_fn,
as_note = FALSE),
as_note = FALSE
),
immediate. = immediate,
call. = call)
call. = call
)
}
# this alternative to the stop() function:
@@ -554,7 +617,8 @@ stop_ifnot <- function(expr, ..., call = TRUE) {
}
ifelse(!is.na(x),
x,
ifelse(!is.na(y), y, NA))
ifelse(!is.na(y), y, NA)
)
}
return_after_integrity_check <- function(value, type, check_vector) {
@@ -565,7 +629,7 @@ return_after_integrity_check <- function(value, type, check_vector) {
value
}
# transforms data set to data.frame with only ASCII values, to comply with CRAN policies
# transforms data set to a tibble with only ASCII values, to comply with CRAN policies
dataset_UTF8_to_ASCII <- function(df) {
trans <- function(vect) {
iconv(vect, from = "UTF-8", to = "ASCII//TRANSLIT")
@@ -587,7 +651,7 @@ dataset_UTF8_to_ASCII <- function(df) {
df[, i] <- col
}
}
df
import_fn("as_tibble", "tibble")(df)
}
# for eucast_rules() and mdro(), creates markdown output with URLs and names
@@ -596,7 +660,7 @@ create_eucast_ab_documentation <- function() {
ab <- character()
for (val in x) {
if (paste0("AB_", val) %in% ls(envir = asNamespace("AMR"))) {
# antibiotic group names, as defined in data-raw/_internals.R, such as `CARBAPENEMS`
# antibiotic group names, as defined in data-raw/_pre_commit_hook.R, such as `CARBAPENEMS`
val <- eval(parse(text = paste0("AB_", val)), envir = asNamespace("AMR"))
} else if (val %in% AB_lookup$ab) {
# separate drugs, such as `AMX`
@@ -638,7 +702,7 @@ vector_or <- function(v, quotes = TRUE, reverse = FALSE, sort = TRUE, initial_ca
if (isTRUE(initial_captital)) {
v[1] <- gsub("^([a-z])", "\\U\\1", v[1], perl = TRUE)
}
if (length(v) == 1) {
if (length(v) <= 1) {
return(paste0(quotes, v, quotes))
}
if (identical(v, c("I", "R", "S"))) {
@@ -646,13 +710,17 @@ vector_or <- function(v, quotes = TRUE, reverse = FALSE, sort = TRUE, initial_ca
v <- c("R", "S", "I")
}
# all commas except for last item, so will become '"val1", "val2", "val3" or "val4"'
paste0(paste0(quotes, v[seq_len(length(v) - 1)], quotes, collapse = ", "),
last_sep, paste0(quotes, v[length(v)], quotes))
paste0(
paste0(quotes, v[seq_len(length(v) - 1)], quotes, collapse = ", "),
last_sep, paste0(quotes, v[length(v)], quotes)
)
}
vector_and <- function(v, quotes = TRUE, reverse = FALSE, sort = TRUE, initial_captital = FALSE) {
vector_or(v = v, quotes = quotes, reverse = reverse, sort = sort,
initial_captital = initial_captital, last_sep = " and ")
vector_or(
v = v, quotes = quotes, reverse = reverse, sort = sort,
initial_captital = initial_captital, last_sep = " and "
)
}
format_class <- function(class, plural = FALSE) {
@@ -664,9 +732,11 @@ format_class <- function(class, plural = FALSE) {
}
class[class == "character"] <- "text string"
class[class %in% c("Date", "POSIXt")] <- "date"
class[class != class.bak] <- paste0(ifelse(plural, "", "a "),
class[class != class.bak] <- paste0(
ifelse(plural, "", "a "),
class[class != class.bak],
ifelse(plural, "s", ""))
ifelse(plural, "s", "")
)
# exceptions
class[class == "logical"] <- ifelse(plural, "a vector of `TRUE`/`FALSE`", "`TRUE` or `FALSE`")
class[class == "data.frame"] <- "a data set"
@@ -707,11 +777,12 @@ meet_criteria <- function(object,
# if object is missing, or another error:
tryCatch(invisible(object),
error = function(e) pkg_env$meet_criteria_error_txt <- e$message)
error = function(e) pkg_env$meet_criteria_error_txt <- e$message
)
if (!is.null(pkg_env$meet_criteria_error_txt)) {
error_txt <- pkg_env$meet_criteria_error_txt
pkg_env$meet_criteria_error_txt <- NULL
stop(error_txt, call. = FALSE) # don't use stop_() here, pkg may not be loaded yet
stop(error_txt, call. = FALSE) # don't use stop_() here, our pkg may not be loaded yet
}
pkg_env$meet_criteria_error_txt <- NULL
@@ -728,14 +799,16 @@ meet_criteria <- function(object,
stop_ifnot(inherits(object, allow_class), "argument `", obj_name,
"` must be ", format_class(allow_class, plural = isTRUE(has_length > 1)),
", i.e. not be ", format_class(class(object), plural = isTRUE(has_length > 1)),
call = call_depth)
call = call_depth
)
# check data.frames for data
if (inherits(object, "data.frame")) {
stop_if(any(dim(object) == 0),
"the data provided in argument `", obj_name,
"` must contain rows and columns (current dimensions: ",
paste(dim(object), collapse = "x"), ")",
call = call_depth)
call = call_depth
)
}
}
if (!is.null(has_length)) {
@@ -743,13 +816,15 @@ meet_criteria <- function(object,
"` must ", # ifelse(allow_NULL, "be NULL or must ", ""),
"be of length ", vector_or(has_length, quotes = FALSE),
", not ", length(object),
call = call_depth)
call = call_depth
)
}
if (!is.null(looks_like)) {
stop_ifnot(object %like% looks_like, "argument `", obj_name,
"` must ", # ifelse(allow_NULL, "be NULL or must ", ""),
"resemble the regular expression \"", looks_like, "\"",
call = call_depth)
call = call_depth
)
}
if (!is.null(is_in)) {
if (ignore.case == TRUE) {
@@ -759,46 +834,57 @@ meet_criteria <- function(object,
stop_ifnot(all(object %in% is_in, na.rm = TRUE), "argument `", obj_name, "` ",
ifelse(!is.null(has_length) && length(has_length) == 1 && has_length == 1,
"must be either ",
"must only contain values "),
"must only contain values "
),
vector_or(is_in, quotes = !isTRUE(any(c("double", "numeric", "integer") %in% allow_class))),
ifelse(allow_NA == TRUE, ", or NA", ""),
call = call_depth)
call = call_depth
)
}
if (isTRUE(is_positive)) {
stop_if(is.numeric(object) && !all(object > 0, na.rm = TRUE), "argument `", obj_name,
"` must ",
ifelse(!is.null(has_length) && length(has_length) == 1 && has_length == 1,
"be a number higher than zero",
"all be numbers higher than zero"),
call = call_depth)
"all be numbers higher than zero"
),
call = call_depth
)
}
if (isTRUE(is_positive_or_zero)) {
stop_if(is.numeric(object) && !all(object >= 0, na.rm = TRUE), "argument `", obj_name,
"` must ",
ifelse(!is.null(has_length) && length(has_length) == 1 && has_length == 1,
"be zero or a positive number",
"all be zero or numbers higher than zero"),
call = call_depth)
"all be zero or numbers higher than zero"
),
call = call_depth
)
}
if (isTRUE(is_finite)) {
stop_if(is.numeric(object) && !all(is.finite(object[!is.na(object)]), na.rm = TRUE), "argument `", obj_name,
"` must ",
ifelse(!is.null(has_length) && length(has_length) == 1 && has_length == 1,
"be a finite number",
"all be finite numbers"),
"all be finite numbers"
),
" (i.e. not be infinite)",
call = call_depth)
call = call_depth
)
}
if (!is.null(contains_column_class)) {
stop_ifnot(any(vapply(FUN.VALUE = logical(1),
stop_ifnot(any(vapply(
FUN.VALUE = logical(1),
object,
function(col, columns_class = contains_column_class) {
inherits(col, columns_class)
}), na.rm = TRUE),
}
), na.rm = TRUE),
"the data provided in argument `", obj_name,
"` must contain at least one column of class <", contains_column_class, ">. ",
"See ?as.", contains_column_class, ".",
call = call_depth)
call = call_depth
)
}
return(invisible())
}
@@ -827,11 +913,9 @@ get_current_data <- function(arg_name, call) {
# an element `.data` will be in the environment when using `dplyr::select()`
# (but not when using `dplyr::filter()`, `dplyr::mutate()` or `dplyr::summarise()`)
return(env$`.data`)
} else if (valid_df(env$xx)) {
# an element `xx` will be in the environment for rows + cols, e.g. `example_isolates[c(1:3), carbapenems()]`
return(env$xx)
} else if (valid_df(env$x)) {
# an element `x` will be in the environment for only cols, e.g. `example_isolates[, carbapenems()]`
return(env$x)
@@ -843,17 +927,20 @@ get_current_data <- function(arg_name, call) {
if (is.na(arg_name)) {
if (isTRUE(is.numeric(call))) {
fn <- as.character(sys.call(call + 1)[1])
examples <- paste0(", e.g.:\n",
examples <- paste0(
", e.g.:\n",
" your_data %>% select(", fn, "())\n",
" your_data %>% select(column_a, column_b, ", fn, "())\n",
" your_data[, ", fn, "()]\n",
' your_data[, c("column_a", "column_b", ', fn, "())]")
' your_data[, c("column_a", "column_b", ', fn, "())]"
)
} else {
examples <- ""
}
stop_("this function must be used inside a `dplyr` verb or `data.frame` call",
examples,
call = call)
call = call
)
} else {
# mimic a base R error that the argument is missing
stop_("argument `", arg_name, "` is missing with no default", call = call)
@@ -917,13 +1004,17 @@ unique_call_id <- function(entire_session = FALSE, match_fn = NULL) {
for (i in seq_len(length(calls))) {
call_clean <- gsub("[^a-zA-Z0-9_().-]", "", as.character(calls[[i]]), perl = TRUE)
if (any(call_clean %like% paste0(match_fn, "\\("), na.rm = TRUE)) {
return(c(envir = gsub("<environment: (.*)>", "\\1", utils::capture.output(sys.frames()[[1]]), perl = TRUE),
call = paste0(deparse(calls[[i]]), collapse = "")))
return(c(
envir = gsub("<environment: (.*)>", "\\1", utils::capture.output(sys.frames()[[1]]), perl = TRUE),
call = paste0(deparse(calls[[i]]), collapse = "")
))
}
}
}
c(envir = paste0(sample(c(c(0:9), letters[1:6]), size = 32, replace = TRUE), collapse = ""),
call = paste0(sample(c(c(0:9), letters[1:6]), size = 32, replace = TRUE), collapse = ""))
c(
envir = paste0(sample(c(c(0:9), letters[1:6]), size = 32, replace = TRUE), collapse = ""),
call = paste0(sample(c(c(0:9), letters[1:6]), size = 32, replace = TRUE), collapse = "")
)
}
#' @noRd
@@ -932,17 +1023,23 @@ unique_call_id <- function(entire_session = FALSE, match_fn = NULL) {
#' @param entire_session show message once per session
message_not_thrown_before <- function(fn, ..., entire_session = FALSE) {
# this is to prevent that messages/notes will be printed for every dplyr group or more than once per session
# e.g. this would show a msg 4 times: example_isolates %>% group_by(hospital_id) %>% filter(mo_is_gram_negative())
# e.g. this would show a msg 4 times: example_isolates %>% group_by(ward) %>% filter(mo_is_gram_negative())
salt <- gsub("[^a-zA-Z0-9|_-]", "?", paste(c(...), sep = "|", collapse = "|"), perl = TRUE)
not_thrown_before <- is.null(pkg_env[[paste0("thrown_msg.", fn, ".", salt)]]) ||
!identical(pkg_env[[paste0("thrown_msg.", fn, ".", salt)]],
unique_call_id(entire_session = entire_session,
match_fn = fn))
!identical(
pkg_env[[paste0("thrown_msg.", fn, ".", salt)]],
unique_call_id(
entire_session = entire_session,
match_fn = fn
)
)
if (isTRUE(not_thrown_before)) {
# message was not thrown before - remember this so on the next run it will return FALSE:
assign(x = paste0("thrown_msg.", fn, ".", salt),
assign(
x = paste0("thrown_msg.", fn, ".", salt),
value = unique_call_id(entire_session = entire_session, match_fn = fn),
envir = pkg_env)
envir = pkg_env
)
}
not_thrown_before
}
@@ -965,8 +1062,12 @@ has_colour <- function() {
if ((cols <- Sys.getenv("RSTUDIO_CONSOLE_COLOR", "")) != "" && !is.na(as.double(cols))) {
return(TRUE)
}
tryCatch(get("isAvailable", envir = asNamespace("rstudioapi"))(), error = function(e) return(FALSE)) &&
tryCatch(get("hasFun", envir = asNamespace("rstudioapi"))("getConsoleHasColor"), error = function(e) return(FALSE))
tryCatch(get("isAvailable", envir = asNamespace("rstudioapi"))(), error = function(e) {
return(FALSE)
}) &&
tryCatch(get("hasFun", envir = asNamespace("rstudioapi"))("getConsoleHasColor"), error = function(e) {
return(FALSE)
})
}
if (rstudio_with_ansi_support() && sink.number() == 0) {
return(TRUE)
@@ -989,10 +1090,12 @@ has_colour <- function() {
if (Sys.getenv("TERM") == "dumb") {
return(FALSE)
}
grepl(pattern = "^screen|^xterm|^vt100|color|ansi|cygwin|linux",
grepl(
pattern = "^screen|^xterm|^vt100|color|ansi|cygwin|linux",
x = Sys.getenv("TERM"),
ignore.case = TRUE,
perl = TRUE)
perl = TRUE
)
}
# set colours if console has_colour()
@@ -1051,15 +1154,15 @@ font_green_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[42m", after = "\033[49m", collapse = collapse)
}
font_rsi_R_bg <- function(..., collapse = " ") {
#ED553B
# ED553B
try_colour(..., before = "\033[48;5;203m", after = "\033[49m", collapse = collapse)
}
font_rsi_S_bg <- function(..., collapse = " ") {
#3CAEA3
# 3CAEA3
try_colour(..., before = "\033[48;5;79m", after = "\033[49m", collapse = collapse)
}
font_rsi_I_bg <- function(..., collapse = " ") {
#F6D55C
# F6D55C
try_colour(..., before = "\033[48;5;222m", after = "\033[49m", collapse = collapse)
}
font_red_bg <- function(..., collapse = " ") {
@@ -1101,8 +1204,10 @@ progress_ticker <- function(n = 1, n_min = 0, print = TRUE, ...) {
if (!is.null(progress_bar)) {
# so we use progress::progress_bar
# a close() method was also added, see below this function
pb <- progress_bar$new(format = "[:bar] :percent (:current/:total)",
total = n)
pb <- progress_bar$new(
format = "[:bar] :percent (:current/:total)",
total = n
)
} else {
pb <- utils::txtProgressBar(max = n, style = 3)
pb$tick <- function() {
@@ -1153,6 +1258,19 @@ create_pillar_column <- function(x, ...) {
new_pillar_shaft_simple(x, ...)
}
as_original_data_class <- function(df, old_class = NULL) {
if ("tbl_df" %in% old_class && pkg_is_available("tibble", also_load = FALSE)) {
fn <- import_fn("as_tibble", "tibble")
} else if ("tbl_ts" %in% old_class && pkg_is_available("tsibble", also_load = FALSE)) {
fn <- import_fn("as_tsibble", "tsibble")
} else if ("data.table" %in% old_class && pkg_is_available("data.table", also_load = FALSE)) {
fn <- import_fn("as.data.table", "data.table")
} else {
fn <- base::as.data.frame
}
fn(df)
}
# copied from vctrs::s3_register by their permission:
# https://github.com/r-lib/vctrs/blob/05968ce8e669f73213e3e894b5f4424af4f46316/R/register-s3.R
s3_register <- function(generic, class, method = NULL) {
@@ -1167,16 +1285,14 @@ s3_register <- function(generic, class, method = NULL) {
top <- topenv(caller)
if (isNamespace(top)) {
asNamespace(environmentName(top))
}
else {
} else {
caller
}
}
get_method <- function(method, env) {
if (is.null(method)) {
get(paste0(generic, ".", class), envir = get_method_env())
}
else {
} else {
method
}
}
@@ -1202,19 +1318,30 @@ s3_register <- function(generic, class, method = NULL) {
round2 <- function(x, digits = 1, force_zero = TRUE) {
x <- as.double(x)
# https://stackoverflow.com/a/12688836/4575331
val <- (trunc((abs(x) * 10 ^ digits) + 0.5) / 10 ^ digits) * sign(x)
val <- (trunc((abs(x) * 10^digits) + 0.5) / 10^digits) * sign(x)
if (digits > 0 & force_zero == TRUE) {
values_trans <- val[val != as.integer(val) & !is.na(val)]
val[val != as.integer(val) & !is.na(val)] <- paste0(values_trans,
strrep("0",
max(0,
val[val != as.integer(val) & !is.na(val)] <- paste0(
values_trans,
strrep(
"0",
max(
0,
digits - nchar(
format(
as.double(
gsub(".*[.](.*)$",
gsub(
".*[.](.*)$",
"\\1",
values_trans)),
scientific = FALSE)))))
values_trans
)
),
scientific = FALSE
)
)
)
)
)
}
as.double(val)
}
@@ -1231,12 +1358,20 @@ percentage <- function(x, digits = NULL, ...) {
if (minimum > maximum) {
minimum <- maximum
}
max_places <- max(unlist(lapply(strsplit(sub("0+$", "",
as.character(x * 100)), ".", fixed = TRUE),
function(y) ifelse(length(y) == 2, nchar(y[2]), 0))), na.rm = TRUE)
max_places <- max(unlist(lapply(
strsplit(sub(
"0+$", "",
as.character(x * 100)
), ".", fixed = TRUE),
function(y) ifelse(length(y) == 2, nchar(y[2]), 0)
)), na.rm = TRUE)
max(min(max_places,
maximum, na.rm = TRUE),
minimum, na.rm = TRUE)
maximum,
na.rm = TRUE
),
minimum,
na.rm = TRUE
)
}
# format_percentage() function
@@ -1253,7 +1388,8 @@ percentage <- function(x, digits = NULL, ...) {
scientific = FALSE,
digits = max(1, digits),
nsmall = digits,
...)
...
)
x_formatted <- paste0(x_formatted, "%")
x_formatted[!grepl(pattern = "^[0-9.,e-]+$", x = x)] <- NA_character_
x_formatted
@@ -1265,9 +1401,12 @@ percentage <- function(x, digits = NULL, ...) {
# max one digit if undefined
digits <- getdecimalplaces(x, minimum = 0, maximum = 1)
}
format_percentage(structure(.Data = as.double(x),
class = c("percentage", "numeric")),
digits = digits, ...)
format_percentage(structure(
.Data = as.double(x),
class = c("percentage", "numeric")
),
digits = digits, ...
)
}
time_start_tracking <- function() {
@@ -1283,13 +1422,16 @@ time_track <- function(name = NULL) {
# see here for the full list: https://github.com/r-lib/backports
strrep <- function(x, times) {
x <- as.character(x)
if (length(x) == 0L)
if (length(x) == 0L) {
return(x)
}
unlist(.mapply(function(x, times) {
if (is.na(x) || is.na(times))
if (is.na(x) || is.na(times)) {
return(NA_character_)
if (times <= 0L)
}
if (times <= 0L) {
return("")
}
paste0(replicate(times, x), collapse = "")
}, list(x = x, times = times), MoreArgs = list()), use.names = FALSE)
}
@@ -1299,7 +1441,8 @@ trimws <- function(x, which = c("both", "left", "right"), whitespace = "[ \t\r\n
switch(which,
left = mysub(paste0("^", whitespace, "+"), x),
right = mysub(paste0(whitespace, "+$"), x),
both = mysub(paste0(whitespace, "+$"), mysub(paste0("^", whitespace, "+"), x)))
both = mysub(paste0(whitespace, "+$"), mysub(paste0("^", whitespace, "+"), x))
)
}
isFALSE <- function(x) {
is.logical(x) && length(x) == 1L && !is.na(x) && !x
@@ -1333,7 +1476,7 @@ if (getRversion() < "3.1") {
sinpi <- function(...) 1
tanpi <- function(...) 1
}
dir.exists <- function (paths) {
x = base::file.info(paths)$isdir
dir.exists <- function(paths) {
x <- base::file.info(paths)$isdir
!is.na(x) & x
}
+50 -23
View File
@@ -206,7 +206,9 @@ pm_distinct <- function(.data, ...) {
}
pm_distinct.default <- function(.data, ..., .keep_all = FALSE) {
if (ncol(.data) == 0L) return(.data[1, ])
if (ncol(.data) == 0L) {
return(.data[1, ])
}
cols <- pm_deparse_dots(...)
col_names <- names(cols)
col_len <- length(cols)
@@ -336,7 +338,9 @@ pm_print.grouped_data <- function(x, ..., digits = NULL, quote = FALSE, right =
}
pm_group_data <- function(.data) {
if (!pm_has_groups(.data)) return(data.frame(.rows = I(list(seq_len(nrow(.data))))))
if (!pm_has_groups(.data)) {
return(data.frame(.rows = I(list(seq_len(nrow(.data))))))
}
pm_groups <- pm_get_groups(.data)
pm_group_data_worker(.data, pm_groups)
}
@@ -360,7 +364,9 @@ pm_group_rows <- function(.data) {
}
pm_group_indices <- function(.data) {
if (!pm_has_groups(.data)) return(rep(1L, nrow(.data)))
if (!pm_has_groups(.data)) {
return(rep(1L, nrow(.data)))
}
pm_groups <- pm_get_groups(.data)
res <- unique(.data[, pm_groups, drop = FALSE])
res <- res[do.call(order, lapply(pm_groups, function(x) res[, x])), , drop = FALSE]
@@ -417,7 +423,9 @@ pm_group_keys <- function(.data) {
pm_context$setup(.data)
res <- pm_context$.data[, pm_context$get_colnames() %in% pm_groups, drop = FALSE]
res <- res[!duplicated(res), , drop = FALSE]
if (nrow(res) == 0L) return(res)
if (nrow(res) == 0L) {
return(res)
}
class(res) <- "data.frame"
res <- res[do.call(order, lapply(pm_groups, function(x) res[, x])), , drop = FALSE]
rownames(res) <- NULL
@@ -509,7 +517,9 @@ pm_join_message <- function(by) {
pm_lag <- function(x, pm_n = 1L, default = NA) {
if (inherits(x, "ts")) stop("`x` must be a vector, not a `ts` object, do you want `stats::pm_lag()`?")
if (length(pm_n) != 1L || !is.numeric(pm_n) || pm_n < 0L) stop("`pm_n` must be a nonnegative integer scalar")
if (pm_n == 0L) return(x)
if (pm_n == 0L) {
return(x)
}
tryCatch(
storage.mode(default) <- typeof(x),
warning = function(w) {
@@ -525,7 +535,9 @@ pm_lag <- function(x, pm_n = 1L, default = NA) {
pm_lead <- function(x, pm_n = 1L, default = NA) {
if (length(pm_n) != 1L || !is.numeric(pm_n) || pm_n < 0L) stop("pm_n must be a nonnegative integer scalar")
if (pm_n == 0L) return(x)
if (pm_n == 0L) {
return(x)
}
tryCatch(
storage.mode(default) <- typeof(x),
warning = function(w) {
@@ -565,7 +577,9 @@ pm_mutate.grouped_data <- function(.data, ...) {
}
pm_n_distinct <- function(..., na.rm = FALSE) {
res <- c(...)
if (is.list(res)) return(nrow(unique(as.data.frame(res, stringsAsFactors = FALSE))))
if (is.list(res)) {
return(nrow(unique(as.data.frame(res, stringsAsFactors = FALSE))))
}
if (isTRUE(na.rm)) res <- res[!is.na(res)]
length(unique(res))
}
@@ -593,7 +607,7 @@ pm_pull <- function(.data, var = -1) {
} else if (var_deparse %in% col_names) {
var <- var_deparse
}
.data[, var]
.data[, var, drop = TRUE]
}
pm_set_names <- function(object = nm, nm) {
names(object) <- nm
@@ -669,15 +683,16 @@ pm_rename_with <- function(.data, .fn, .cols = pm_everything(), ...) {
.data
}
pm_replace_with <- function(x, i, val, arg_name) {
if (is.null(val)) return(x)
if (is.null(val)) {
return(x)
}
pm_check_length(val, x, arg_name)
pm_check_type(val, x, arg_name)
pm_check_class(val, x, arg_name)
i[is.na(i)] <- FALSE
if (length(val) == 1L) {
x[i] <- val
}
else {
} else {
x[i] <- val[i]
}
x
@@ -686,7 +701,9 @@ pm_replace_with <- function(x, i, val, arg_name) {
pm_check_length <- function(x, y, arg_name) {
length_x <- length(x)
length_y <- length(y)
if (all(length_x %in% c(1L, length_y))) return()
if (all(length_x %in% c(1L, length_y))) {
return()
}
if (length_y == 1) {
stop(arg_name, " must be length 1, not ", paste(length_x, sep = ", "))
} else {
@@ -697,15 +714,21 @@ pm_check_length <- function(x, y, arg_name) {
pm_check_type <- function(x, y, arg_name) {
x_type <- typeof(x)
y_type <- typeof(y)
if (identical(x_type, y_type)) return()
if (identical(x_type, y_type)) {
return()
}
stop(arg_name, " must be `", y_type, "`, not `", x_type, "`")
}
pm_check_class <- function(x, y, arg_name) {
if (!is.object(x)) return()
if (!is.object(x)) {
return()
}
exp_classes <- class(y)
out_classes <- class(x)
if (identical(out_classes, exp_classes)) return()
if (identical(out_classes, exp_classes)) {
return()
}
stop(arg_name, " must have class `", exp_classes, "`, not class `", out_classes, "`")
}
pm_rownames_to_column <- function(.data, var = "rowname") {
@@ -827,8 +850,7 @@ pm_select_positions <- function(.data, ..., .group_pos = FALSE) {
pm_eval_expr <- function(x) {
type <- typeof(x)
switch(
type,
switch(type,
"integer" = x,
"double" = as.integer(x),
"character" = pm_select_char(x),
@@ -864,8 +886,7 @@ pm_select_symbol <- function(expr) {
pm_eval_call <- function(x) {
type <- as.character(x[[1]])
switch(
type,
switch(type,
`:` = pm_select_seq(x),
`!` = pm_select_negate(x),
`-` = pm_select_minus(x),
@@ -1029,7 +1050,7 @@ pm_is_wholenumber <- function(x) {
x %% 1L == 0L
}
pm_seq2 <- function (from, to) {
pm_seq2 <- function(from, to) {
if (length(from) != 1) stop("`from` must be length one")
if (length(to) != 1) stop("`to` must be length one")
if (from > to) integer() else seq.int(from, to)
@@ -1041,19 +1062,25 @@ pm_is_function <- function(x, frame) {
warning = function(w) FALSE,
error = function(e) FALSE
)
if (isTRUE(res)) return(res)
if (isTRUE(res)) {
return(res)
}
res <- tryCatch(
is.function(eval(x)),
warning = function(w) FALSE,
error = function(e) FALSE
)
if (isTRUE(res)) return(res)
if (isTRUE(res)) {
return(res)
}
res <- tryCatch(
is.function(eval(as.symbol(deparse(substitute(x))))),
warning = function(w) FALSE,
error = function(e) FALSE
)
if (isTRUE(res)) return(res)
if (isTRUE(res)) {
return(res)
}
FALSE
}
+77 -43
View File
@@ -26,7 +26,6 @@
#' Transform Input to an Antibiotic ID
#'
#' Use this function to determine the antibiotic code of one or more antibiotics. The data set [antibiotics] will be searched for abbreviations, official names and synonyms (brand names).
#' @inheritSection lifecycle Stable Lifecycle
#' @param x a [character] vector to determine to antibiotic ID
#' @param flag_multiple_results a [logical] to indicate whether a note should be printed to the console that probably more than one antibiotic code or name can be retrieved from a single input value.
#' @param info a [logical] to indicate whether a progress bar should be printed, defaults to `TRUE` only in interactive mode
@@ -55,7 +54,6 @@
#' * [antibiotics] for the [data.frame] that is being used to determine ATCs
#' * [ab_from_text()] for a function to retrieve antimicrobial drugs from clinical text (from health care records)
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' # these examples all return "ERY", the ID of erythromycin:
@@ -86,7 +84,6 @@
#' # you can quickly rename <rsi> columns using dplyr >= 1.0.0:
#' example_isolates %>%
#' rename_with(as.ab, where(is.rsi))
#'
#' }
#' }
as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
@@ -102,7 +99,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
if (all(x %in% c(AB_lookup$ab, NA))) {
# all valid AB codes, but not yet right class
return(set_clean_class(x,
new_class = c("ab", "character")))
new_class = c("ab", "character")
))
}
initial_search <- is.null(list(...)$initial_search)
@@ -127,6 +125,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
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 (initial_search == TRUE & isTRUE(length(from_text) > 1)) {
@@ -135,8 +134,10 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
abnames <- abnames[!abnames %in% c("clavulanic acid", "avibactam")]
}
if (length(abnames) > 1) {
message_("More than one result was found for item ", index, ": ",
vector_and(abnames, quotes = FALSE))
message_(
"More than one result was found for item ", index, ": ",
vector_and(abnames, quotes = FALSE)
)
}
}
found[1L]
@@ -149,12 +150,18 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
known_codes_atc <- vapply(FUN.VALUE = logical(1), x, function(x_) x_ %in% unlist(AB_lookup$atc), USE.NAMES = FALSE)
known_codes_cid <- x %in% AB_lookup$cid
x_new[known_codes_ab] <- AB_lookup$ab[match(x[known_codes_ab], AB_lookup$ab)]
x_new[known_codes_atc] <- AB_lookup$ab[vapply(FUN.VALUE = integer(1),
x_new[known_codes_atc] <- AB_lookup$ab[vapply(
FUN.VALUE = integer(1),
x[known_codes_atc],
function(x_) which(vapply(FUN.VALUE = logical(1),
function(x_) {
which(vapply(
FUN.VALUE = logical(1),
AB_lookup$atc,
function(atc) x_ %in% atc))[1L],
USE.NAMES = FALSE)]
function(atc) x_ %in% atc
))[1L]
},
USE.NAMES = FALSE
)]
x_new[known_codes_cid] <- AB_lookup$ab[match(x[known_codes_cid], AB_lookup$cid)]
already_known <- known_names | known_codes_ab | known_codes_atc | known_codes_cid
@@ -164,7 +171,6 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
for (i in which(!already_known)) {
if (initial_search == TRUE) {
progress$tick()
}
@@ -178,10 +184,18 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
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(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]]),
error = function(e) character(0))
error = function(e) character(0)
)
} else {
from_text <- character(0)
}
@@ -193,8 +207,10 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# exact LOINC code
loinc_found <- unlist(lapply(AB_lookup$generalised_loinc,
function(s) x[i] %in% s))
loinc_found <- unlist(lapply(
AB_lookup$generalised_loinc,
function(s) x[i] %in% s
))
found <- antibiotics$ab[loinc_found == TRUE]
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -202,8 +218,10 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# exact synonym
synonym_found <- unlist(lapply(AB_lookup$generalised_synonyms,
function(s) x[i] %in% s))
synonym_found <- unlist(lapply(
AB_lookup$generalised_synonyms,
function(s) x[i] %in% s
))
found <- antibiotics$ab[synonym_found == TRUE]
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -211,9 +229,11 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# exact abbreviation
abbr_found <- unlist(lapply(AB_lookup$generalised_abbreviations,
abbr_found <- unlist(lapply(
AB_lookup$generalised_abbreviations,
# require at least 2 characters for abbreviations
function(s) x[i] %in% s & nchar(x[i]) >= 2))
function(s) x[i] %in% s & nchar(x[i]) >= 2
))
found <- antibiotics$ab[abbr_found == TRUE]
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -237,7 +257,6 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
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)
@@ -262,21 +281,23 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# try if name starts with it
found <- antibiotics[which(AB_lookup$generalised_name %like% paste0("^", x_spelling)), ]$ab
found <- antibiotics[which(AB_lookup$generalised_name %like% paste0("^", x_spelling)), "ab", 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 <- antibiotics[which(AB_lookup$generalised_name %like% paste0(x_spelling, "$")), ]$ab
found <- antibiotics[which(AB_lookup$generalised_name %like% paste0(x_spelling, "$")), "ab", 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(AB_lookup$generalised_synonyms,
function(s) any(s %like% paste0("^", x_spelling))))
synonym_found <- unlist(lapply(
AB_lookup$generalised_synonyms,
function(s) any(s %like% paste0("^", x_spelling))
))
found <- antibiotics$ab[synonym_found == TRUE]
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -307,19 +328,23 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# transform back from other languages and try again
x_translated <- paste(lapply(strsplit(x[i], "[^A-Z0-9]"),
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])
y[i]
)
}
}
generalise_antibiotic_name(y)
})[[1]],
collapse = "/")
}
)[[1]],
collapse = "/"
)
x_translated_guess <- suppressWarnings(as.ab(x_translated, initial_search = FALSE))
if (!is.na(x_translated_guess)) {
x_new[i] <- x_translated_guess
@@ -327,17 +352,21 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# now also try to coerce brandname combinations like "Amoxy/clavulanic acid"
x_translated <- paste(lapply(strsplit(x_translated, "[^A-Z0-9 ]"),
x_translated <- paste(lapply(
strsplit(x_translated, "[^A-Z0-9 ]"),
function(y) {
for (i in seq_len(length(y))) {
y_name <- suppressWarnings(ab_name(y[i], language = NULL, initial_search = FALSE))
y[i] <- ifelse(!is.na(y_name),
y_name,
y[i])
y[i]
)
}
generalise_antibiotic_name(y)
})[[1]],
collapse = "/")
}
)[[1]],
collapse = "/"
)
x_translated_guess <- suppressWarnings(as.ab(x_translated, initial_search = FALSE))
if (!is.na(x_translated_guess)) {
x_new[i] <- x_translated_guess
@@ -366,7 +395,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
found <- from_text[1L]
} else {
found <- tryCatch(suppressWarnings(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]][1L]),
error = function(e) NA_character_)
error = function(e) NA_character_
)
}
if (!is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -430,7 +460,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
substr(x[i], j + 1, j + 1),
substr(x[i], j, j),
# ending part:
substr(x[i], j + 2, nchar(x[i])))
substr(x[i], j + 2, nchar(x[i]))
)
found <- suppressWarnings(as.ab(x_switched, initial_search = FALSE))
if (!is.na(found)) {
break
@@ -440,7 +471,6 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
x_new[i] <- found[1L]
next
}
} # end of initial_search = TRUE
# not found
@@ -452,16 +482,19 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
# take failed ATC codes apart from rest
x_unknown_ATCs <- x_unknown[x_unknown %like% "[A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9]"]
x_unknown <- x_unknown[!x_unknown %in% x_unknown_ATCs]
if (length(x_unknown_ATCs) > 0 & fast_mode == FALSE) {
warning_("in `as.ab()`: these ATC codes are not (yet) in the antibiotics data set: ",
vector_and(x_unknown_ATCs), ".")
if (length(x_unknown_ATCs) > 0 && fast_mode == FALSE) {
warning_(
"in `as.ab()`: these ATC codes are not (yet) in the antibiotics data set: ",
vector_and(x_unknown_ATCs), "."
)
}
x_unknown <- x_unknown[!x_unknown %in% x_unknown_ATCs]
if (length(x_unknown) > 0 & fast_mode == FALSE) {
warning_("in `as.ab()`: these values could not be coerced to a valid antimicrobial ID: ",
vector_and(x_unknown), ".")
if (length(x_unknown) > 0 && fast_mode == FALSE) {
warning_(
"in `as.ab()`: these values could not be coerced to a valid antimicrobial ID: ",
vector_and(x_unknown), "."
)
}
x_result <- x_new[match(x_bak_clean, x)]
@@ -470,7 +503,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, info = interactive(), ...) {
}
set_clean_class(x_result,
new_class = c("ab", "character"))
new_class = c("ab", "character")
)
}
#' @rdname as.ab
+24 -22
View File
@@ -26,7 +26,6 @@
#' Retrieve Antimicrobial 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 antimicrobial drugs, doses and forms of administration found in the texts.
#' @inheritSection lifecycle Stable Lifecycle
#' @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*
@@ -53,7 +52,6 @@
#' `df %>% mutate(abx = ab_from_text(clinical_text, collapse = "|"))`
#' @export
#' @return A [list], or a [character] if `collapse` is not `NULL`
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # mind the bad spelling of amoxicillin in this line,
#' # straight from a true health care record:
@@ -70,22 +68,28 @@
#' ab_group(abx[[1]])
#'
#' if (require("dplyr")) {
#' tibble(clinical_text = c("given 400mg cipro and 500 mg amox",
#' "started on doxy iv today")) %>%
#' mutate(abx_codes = ab_from_text(clinical_text),
#' tibble(clinical_text = c(
#' "given 400mg cipro and 500 mg amox",
#' "started on doxy iv today"
#' )) %>%
#' mutate(
#' abx_codes = ab_from_text(clinical_text),
#' abx_doses = ab_from_text(clinical_text, type = "doses"),
#' abx_admin = ab_from_text(clinical_text, type = "admin"),
#' abx_coll = ab_from_text(clinical_text, collapse = "|"),
#' abx_coll_names = ab_from_text(clinical_text,
#' collapse = "|",
#' translate_ab = "name"),
#' translate_ab = "name"
#' ),
#' abx_coll_doses = ab_from_text(clinical_text,
#' type = "doses",
#' collapse = "|"),
#' collapse = "|"
#' ),
#' abx_coll_admin = ab_from_text(clinical_text,
#' type = "admin",
#' collapse = "|"))
#'
#' collapse = "|"
#' )
#' )
#' }
#' }
ab_from_text <- function(text,
@@ -114,7 +118,6 @@ ab_from_text <- function(text,
on.exit(close(progress))
if (type %like% "(drug|ab|anti)") {
translate_ab <- get_translate_ab(translate_ab)
if (isTRUE(thorough_search) |
@@ -126,7 +129,6 @@ ab_from_text <- function(text,
out <- as.ab(text_split, ...)
)
})
} else {
# no thorough search
abbr <- unlist(antibiotics$abbreviations)
@@ -138,19 +140,24 @@ ab_from_text <- function(text,
synonyms_part1 <- synonyms[seq_len(0.5 * length(synonyms))]
synonyms_part2 <- synonyms[!synonyms %in% synonyms_part1]
to_regex <- function(x) {
paste0("^(",
paste0(
"^(",
paste0(unique(gsub("[^a-z0-9]+", "", sort(tolower(x)))), collapse = "|"),
").*")
").*"
)
}
result <- lapply(text_split_all, function(text_split) {
progress$tick()
suppressWarnings(
out <- as.ab(unique(c(text_split[text_split %like_case% to_regex(abbr)],
out <- as.ab(
unique(c(
text_split[text_split %like_case% to_regex(abbr)],
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)])
),
...)
text_split[text_split %like_case% to_regex(synonyms_part2)]
)),
...
)
)
})
}
@@ -167,9 +174,7 @@ ab_from_text <- function(text,
}
out
}
})
} else if (type %like% "dos") {
text_split_all <- strsplit(text, " ")
result <- lapply(text_split_all, function(text_split) {
@@ -187,7 +192,6 @@ ab_from_text <- function(text,
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)"]
@@ -199,7 +203,6 @@ ab_from_text <- function(text,
NA_character_
}
})
} else {
stop_("`type` must be either 'drug', 'dose' or 'administration'")
}
@@ -216,5 +219,4 @@ ab_from_text <- function(text,
}
result
}
+64 -36
View File
@@ -26,7 +26,6 @@
#' 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()].
#' @inheritSection lifecycle Stable Lifecycle
#' @param x any (vector of) text that can be coerced to a valid antibiotic 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)`.
@@ -54,7 +53,6 @@
#' @export
#' @seealso [antibiotics]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # all properties:
#' ab_name("AMX") # "Amoxicillin"
@@ -69,8 +67,10 @@
#'
#' # smart lowercase tranformation
#' ab_name(x = c("AMC", "PLB")) # "Amoxicillin/clavulanic acid" "Polymyxin B"
#' ab_name(x = c("AMC", "PLB"),
#' tolower = TRUE) # "amoxicillin/clavulanic acid" "polymyxin B"
#' ab_name(
#' x = c("AMC", "PLB"),
#' tolower = TRUE
#' ) # "amoxicillin/clavulanic acid" "polymyxin B"
#'
#' # defined daily doses (DDD)
#' ab_ddd("AMX", "oral") # 1.5
@@ -101,15 +101,18 @@
#' \donttest{
#' if (require("dplyr")) {
#' example_isolates %>%
#' set_ab_names()
#' set_ab_names() %>%
#' head()
#'
#' # this does the same:
#' example_isolates %>%
#' rename_with(set_ab_names)
#' rename_with(set_ab_names) %>%
#' head()
#'
#' # set_ab_names() works with any AB property:
#' example_isolates %>%
#' set_ab_names(property = "atc")
#' set_ab_names(property = "atc") %>%
#' head()
#'
#' example_isolates %>%
#' set_ab_names(where(is.rsi)) %>%
@@ -125,7 +128,7 @@ ab_name <- function(x, language = get_AMR_locale(), tolower = FALSE, ...) {
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(tolower, allow_class = "logical", has_length = 1)
x <- translate_AMR(ab_validate(x = x, property = "name", ...), language = language, only_affect_ab_names = TRUE)
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"
@@ -166,7 +169,7 @@ ab_tradenames <- function(x, ...) {
ab_group <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(ab_validate(x = x, property = "group", ...), language = language, only_affect_ab_names = TRUE)
translate_into_language(ab_validate(x = x, property = "group", ...), language = language, only_affect_ab_names = TRUE)
}
#' @rdname ab_property
@@ -179,7 +182,8 @@ ab_atc <- function(x, only_first = FALSE, ...) {
atcs <- ab_validate(x = x, property = "atc", ...)
if (only_first == TRUE) {
atcs <- vapply(FUN.VALUE = character(1),
atcs <- vapply(
FUN.VALUE = character(1),
# get only the first ATC code
atcs,
function(x) {
@@ -189,7 +193,8 @@ ab_atc <- function(x, only_first = FALSE, ...) {
} else {
as.character(x[1L])
}
})
}
)
} else if (length(atcs) == 1) {
atcs <- unname(unlist(atcs))
} else {
@@ -204,7 +209,7 @@ ab_atc <- function(x, only_first = FALSE, ...) {
ab_atc_group1 <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(ab_validate(x = x, property = "atc_group1", ...), language = language, only_affect_ab_names = TRUE)
translate_into_language(ab_validate(x = x, property = "atc_group1", ...), language = language, only_affect_ab_names = TRUE)
}
#' @rdname ab_property
@@ -212,7 +217,7 @@ ab_atc_group1 <- function(x, language = get_AMR_locale(), ...) {
ab_atc_group2 <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(ab_validate(x = x, property = "atc_group2", ...), language = language, only_affect_ab_names = TRUE)
translate_into_language(ab_validate(x = x, property = "atc_group2", ...), language = language, only_affect_ab_names = TRUE)
}
#' @rdname ab_property
@@ -240,8 +245,10 @@ ab_ddd <- function(x, administration = "oral", ...) {
units <- list(...)$units
if (!is.null(units) && isTRUE(units)) {
if (message_not_thrown_before("ab_ddd", entire_session = TRUE)) {
warning_("in `ab_ddd()`: using `ab_ddd(..., units = TRUE)` is deprecated, use `ab_ddd_units()` to retrieve units instead.",
"This warning will be shown once per session.")
warning_(
"in `ab_ddd()`: using `ab_ddd(..., units = TRUE)` is deprecated, use `ab_ddd_units()` to retrieve units instead.",
"This warning will be shown once per session."
)
}
ddd_prop <- paste0(ddd_prop, "_units")
} else {
@@ -250,9 +257,11 @@ ab_ddd <- function(x, administration = "oral", ...) {
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.",
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/")
"www.whocc.no/ddd/list_of_ddds_combined_products/"
)
}
out
}
@@ -265,9 +274,11 @@ ab_ddd_units <- function(x, administration = "oral", ...) {
x <- as.ab(x, ...)
if (any(ab_name(x, language = NULL) %like% "/")) {
warning_("in `ab_ddd_units()`: DDDs of combined products are available for different dose combinations and not (yet) part of the AMR package.",
warning_(
"in `ab_ddd_units()`: DDDs of 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/")
"www.whocc.no/ddd/list_of_ddds_combined_products/"
)
}
ddd_prop <- paste0(administration, "_units")
@@ -281,7 +292,8 @@ ab_info <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.ab(x, ...)
list(ab = as.character(x),
list(
ab = as.character(x),
cid = ab_cid(x),
name = ab_name(x, language = language),
group = ab_group(x, language = language),
@@ -290,10 +302,17 @@ ab_info <- function(x, language = get_AMR_locale(), ...) {
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"))))
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")
)
)
)
}
@@ -331,7 +350,7 @@ ab_property <- function(x, property = "name", language = get_AMR_locale(), ...)
meet_criteria(x, allow_NA = TRUE)
meet_criteria(property, is_in = colnames(antibiotics), has_length = 1)
meet_criteria(language, is_in = c(LANGUAGES_SUPPORTED, ""), has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(ab_validate(x = x, property = property, ...), language = language)
translate_into_language(ab_validate(x = x, property = property, ...), language = language)
}
#' @rdname ab_property
@@ -369,7 +388,8 @@ set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale
vars_ab <- as.ab(data, fast_mode = TRUE)
vars <- data[!is.na(vars_ab)]
}
x <- vapply(FUN.VALUE = character(1),
x <- vapply(
FUN.VALUE = character(1),
ab_property(vars, property = property, language = language),
function(x) {
if (property == "atc") {
@@ -383,10 +403,13 @@ set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale
as.character(x[1L])
}
},
USE.NAMES = FALSE)
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))
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)]
}
@@ -398,7 +421,8 @@ set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale
# 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),
invisible(lapply(
unique(x),
function(u) {
dups <- which(x == u)
if (length(dups) > 1) {
@@ -406,7 +430,8 @@ set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale
dup_add_int <- dups[2:length(dups)]
x[dup_add_int] <<- paste0(x[dup_add_int], "_", c(2:length(dups)))
}
}))
}
))
}
if (is.data.frame(data)) {
colnames(data)[colnames(data) %in% vars] <- x
@@ -418,24 +443,27 @@ set_ab_names <- function(data, ..., property = "name", language = get_AMR_locale
}
ab_validate <- function(x, property, ...) {
check_dataset_integrity()
if (tryCatch(all(x[!is.na(x)] %in% AB_lookup$ab), error = function(e) FALSE)) {
# special case for ab_* functions where class is already <ab>
x <- AB_lookup[match(x, 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% antibiotics[1, property],
error = function(e) stop(e$message, call. = FALSE))
tryCatch(x[1L] %in% antibiotics[1, property, drop = TRUE],
error = function(e) stop(e$message, call. = FALSE)
)
if (!all(x %in% AB_lookup[, property])) {
if (!all(x %in% AB_lookup[, property, drop = TRUE])) {
x <- as.ab(x, ...)
if (all(is.na(x)) && is.list(AB_lookup[, property, drop = TRUE])) {
x <- rep(NA_character_, length(x))
} else {
x <- AB_lookup[match(x, AB_lookup$ab), property, drop = TRUE]
}
}
}
if (property == "ab") {
return(set_clean_class(x, new_class = c("ab", "character")))
+168 -79
View File
@@ -26,7 +26,6 @@
#' Antibiotic Selectors
#'
#' These functions allow for filtering rows and selecting columns based on antibiotic test results that are of a specific antibiotic class or group, without the need to define the columns or antibiotic abbreviations. In short, if you have a column name that resembles an antimicrobial agent, it will be picked up by any of these functions that matches its pharmaceutical class: "cefazolin", "CZO" and "J01DB04" will all be picked up by [cephalosporins()].
#' @inheritSection lifecycle Stable Lifecycle
#' @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_rsi_columns a [logical] to indicate whether only columns of class `<rsi>` must be selected (defaults to `FALSE`), see [as.rsi()]
@@ -46,10 +45,11 @@
#' @return (internally) a [character] vector of column names, with additional class `"ab_selector"`
#' @export
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
#' example_isolates
#'
#' # base R ------------------------------------------------------------------
#'
@@ -92,69 +92,95 @@
#' \donttest{
#' if (require("dplyr")) {
#'
#' # get AMR for all aminoglycosides e.g., per hospital:
#' # get AMR for all aminoglycosides e.g., per ward:
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' 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(hospital_id) %>%
#' 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(hospital_id) %>%
#' 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"))
#' 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")
#' #> i Assuming a filter on all 4 aminoglycosides.
#' }
#' 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 macrolides in Gram-positives:
#' # get bug/drug combinations for only glycopeptides in Gram-positives:
#' example_isolates %>%
#' filter(mo_is_gram_positive()) %>%
#' select(mo, macrolides()) %>%
#' select(mo, glycopeptides()) %>%
#' bug_drug_combinations() %>%
#' format()
#'
#' data.frame(some_column = "some_value",
#' J01CA01 = "S") %>% # ATC code of ampicillin
#' }
#' 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 dplyr 1.0.0 and higher (that adds 'across()'), this is all equal:
#' example_isolates[carbapenems() == "R", ]
#' example_isolates %>% filter(carbapenems() == "R")
#' example_isolates %>% filter(across(carbapenems(), ~.x == "R"))
#' # 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)
#' }
#' }
ab_class <- function(ab_class,
@@ -181,19 +207,25 @@ ab_selector <- function(filter,
# 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_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "ab_selector")
ab_in_data <- get_column_abx(vars_df,
info = FALSE, only_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "ab_selector"
)
call <- substitute(filter)
agents <- tryCatch(AMR::antibiotics[which(eval(call, envir = AMR::antibiotics)), "ab", drop = TRUE],
error = function(e) stop_(e$message, call = -5))
error = function(e) stop_(e$message, call = -5)
)
agents <- ab_in_data[ab_in_data %in% agents]
message_agent_names(function_name = "ab_selector",
message_agent_names(
function_name = "ab_selector",
agents = agents,
ab_group = NULL,
examples = "",
call = call)
call = call
)
structure(unname(agents),
class = c("ab_selector", "character"))
class = c("ab_selector", "character")
)
}
#' @rdname antibiotic_class_selectors
@@ -384,24 +416,34 @@ administrable_per_os <- function(only_rsi_columns = FALSE, ...) {
# 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_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "administrable_per_os")
ab_in_data <- get_column_abx(vars_df,
info = FALSE, only_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "administrable_per_os"
)
agents_all <- antibiotics[which(!is.na(antibiotics$oral_ddd)), "ab", drop = TRUE]
agents <- antibiotics[which(antibiotics$ab %in% ab_in_data & !is.na(antibiotics$oral_ddd)), "ab", drop = TRUE]
agents <- ab_in_data[ab_in_data %in% agents]
message_agent_names(function_name = "administrable_per_os",
message_agent_names(
function_name = "administrable_per_os",
agents = agents,
ab_group = "administrable_per_os",
examples = paste0(" (such as ",
examples = paste0(
" (such as ",
vector_or(ab_name(sample(agents_all,
size = min(5, length(agents_all)),
replace = FALSE),
replace = FALSE
),
tolower = TRUE,
language = NULL),
quotes = FALSE),
")"))
language = NULL
),
quotes = FALSE
),
")"
)
)
structure(unname(agents),
class = c("ab_selector", "character"))
class = c("ab_selector", "character")
)
}
#' @rdname antibiotic_class_selectors
@@ -412,17 +454,22 @@ administrable_iv <- function(only_rsi_columns = FALSE, ...) {
# 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_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "administrable_iv")
ab_in_data <- get_column_abx(vars_df,
info = FALSE, only_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "administrable_iv"
)
agents_all <- antibiotics[which(!is.na(antibiotics$iv_ddd)), "ab", drop = TRUE]
agents <- antibiotics[which(antibiotics$ab %in% ab_in_data & !is.na(antibiotics$iv_ddd)), "ab", drop = TRUE]
agents <- ab_in_data[ab_in_data %in% agents]
message_agent_names(function_name = "administrable_iv",
message_agent_names(
function_name = "administrable_iv",
agents = agents,
ab_group = "administrable_iv",
examples = "")
examples = ""
)
structure(unname(agents),
class = c("ab_selector", "character"))
class = c("ab_selector", "character")
)
}
#' @rdname antibiotic_class_selectors
@@ -435,17 +482,26 @@ not_intrinsic_resistant <- function(only_rsi_columns = FALSE, col_mo = NULL, ver
# 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_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "not_intrinsic_resistant")
ab_in_data <- get_column_abx(vars_df,
info = FALSE, only_rsi_columns = only_rsi_columns,
sort = FALSE, fn = "not_intrinsic_resistant"
)
# intrinsic vars
vars_df_R <- tryCatch(sapply(eucast_rules(vars_df,
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))
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 &&
@@ -454,16 +510,19 @@ not_intrinsic_resistant <- function(only_rsi_columns = FALSE, col_mo = NULL, ver
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 ",
message_(
"For `not_intrinsic_resistant()` removing ",
ifelse(length(agents) == 1, "column ", "columns "),
vector_and(agents_formatted, quotes = FALSE, sort = FALSE))
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"))
class = c("ab_selector", "character")
)
}
ab_select_exec <- function(function_name,
@@ -474,20 +533,26 @@ ab_select_exec <- function(function_name,
# 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_rsi_columns = only_rsi_columns,
sort = FALSE, fn = function_name)
ab_in_data <- get_column_abx(vars_df,
info = FALSE, only_rsi_columns = only_rsi_columns,
sort = FALSE, fn = function_name
)
# untreatable drugs
if (only_treatable == TRUE) {
untreatable <- antibiotics[which(antibiotics$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 agents were ignored since they cannot be used for treating patients: ",
warning_(
"in `", function_name, "()`: some agents 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),
tolower = TRUE
),
quotes = FALSE,
sort = TRUE), ". They can be included using `", function_name, "(only_treatable = FALSE)`. ",
"This warning will be shown once per session.")
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]
}
@@ -499,20 +564,24 @@ ab_select_exec <- function(function_name,
}
if (is.null(ab_class_args)) {
# their upper case equivalent are vectors with class <ab>, created in data-raw/_internals.R
# 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"))
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), ")")
language = NULL
),
quotes = FALSE
), ")")
} else {
# this for the 'manual' ab_class() function
abx <- subset(AB_lookup,
abx <- subset(
AB_lookup,
group %like% ab_class_args |
atc_group1 %like% ab_class_args |
atc_group2 %like% ab_class_args)$ab
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), ")")
@@ -521,14 +590,17 @@ ab_select_exec <- function(function_name,
# get the columns with a group names in the chosen ab class
agents <- ab_in_data[names(ab_in_data) %in% abx]
message_agent_names(function_name = function_name,
message_agent_names(
function_name = function_name,
agents = agents,
ab_group = ab_group,
examples = examples,
ab_class_args = ab_class_args)
ab_class_args = ab_class_args
)
structure(unname(agents),
class = c("ab_selector", "character"))
class = c("ab_selector", "character")
)
}
#' @method c ab_selector
@@ -536,7 +608,8 @@ ab_select_exec <- function(function_name,
#' @noRd
c.ab_selector <- function(...) {
structure(unlist(lapply(list(...), as.character)),
class = c("ab_selector", "character"))
class = c("ab_selector", "character")
)
}
all_any_ab_selector <- function(type, ..., na.rm = TRUE) {
@@ -556,10 +629,12 @@ all_any_ab_selector <- function(type, ..., na.rm = TRUE) {
}
x_transposed <- as.list(as.data.frame(t(df[, cols_ab, drop = FALSE]), stringsAsFactors = FALSE))
vapply(FUN.VALUE = logical(1),
vapply(
FUN.VALUE = logical(1),
X = x_transposed,
FUN = function(y) scope_fn(y %in% result, na.rm = na.rm),
USE.NAMES = FALSE)
USE.NAMES = FALSE
)
}
#' @method all ab_selector
@@ -619,12 +694,15 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
} 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.")
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"))
class = c("ab_selector_any_all", "logical")
)
}
#' @method != ab_selector
@@ -641,15 +719,18 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
} 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.")
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
rsi <- c("R", "S", "I")
e2 <- rsi[rsi != e2]
structure(all_any_ab_selector(type = type, e1, e2),
class = c("ab_selector_any_all", "logical"))
class = c("ab_selector_any_all", "logical")
)
}
#' @method & ab_selector
@@ -659,7 +740,8 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
# 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"))
class = c("ab_selector", "character")
)
}
#' @method | ab_selector
#' @export
@@ -668,7 +750,8 @@ any.ab_selector_any_all <- function(..., na.rm = FALSE) {
# 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"))
class = c("ab_selector", "character")
)
}
is_any <- function(el1) {
@@ -715,8 +798,10 @@ find_ab_names <- function(ab_group, n = 3) {
}
vector_or(ab_name(sample(drugs, size = min(n, length(drugs)), replace = FALSE),
tolower = TRUE,
language = NULL),
quotes = FALSE)
language = NULL
),
quotes = FALSE
)
}
message_agent_names <- function(function_name, agents, ab_group = NULL, examples = "", ab_class_args = NULL, call = NULL) {
@@ -736,15 +821,19 @@ message_agent_names <- function(function_name, agents, ab_group = NULL, examples
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, "(",
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))
vector_and(agents_formatted, quotes = FALSE, sort = FALSE)
)
}
}
}
+29 -16
View File
@@ -25,8 +25,7 @@
#' Age in Years of Individuals
#'
#' Calculates age in years based on a reference date, which is the sytem date at default.
#' @inheritSection lifecycle Stable Lifecycle
#' 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) (defaults to 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).
@@ -37,16 +36,20 @@
#' 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.
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' # 10 random birth dates
#' df <- data.frame(birth_date = Sys.Date() - runif(10) * 25000)
#' # 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"))
@@ -70,21 +73,27 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
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))
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")
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"))
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
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
@@ -115,7 +124,6 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
#' Split Ages into Age Groups
#'
#' Split ages into age groups defined by the `split` argument. This allows for easier demographic (antimicrobial resistance) analysis.
#' @inheritSection lifecycle Stable Lifecycle
#' @param x age, e.g. calculated with [age()]
#' @param split_at values to split `x` at, defaults to 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
@@ -131,7 +139,7 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
#' @return Ordered [factor]
#' @seealso To determine ages, based on one or more reference dates, use the [age()] function.
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' ages <- c(3, 8, 16, 54, 31, 76, 101, 43, 21)
#'
@@ -150,7 +158,7 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
#' age_groups(ages, split_at = "fives")
#'
#' # split specifically for children
#' age_groups(ages, c(1, 2, 4, 6, 13, 17))
#' age_groups(ages, c(1, 2, 4, 6, 13, 18))
#' age_groups(ages, "children")
#'
#' \donttest{
@@ -158,10 +166,15 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter_first_isolate() %>%
#' filter(mo == as.mo("E. coli")) %>%
#' filter(mo == as.mo("Escherichia coli")) %>%
#' group_by(age_group = age_groups(age)) %>%
#' select(age_group, CIP) %>%
#' ggplot_rsi(x = "age_group", minimum = 0)
#' ggplot_rsi(
#' 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) {
+3 -5
View File
@@ -52,13 +52,11 @@
#' - Principal component analysis for AMR
#'
#' @section Reference Data Publicly Available:
#' All reference data sets (about microorganisms, antibiotics, R/SI 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.
#' @section Read more on Our Website!:
#' On our website <https://msberends.github.io/AMR/> you can find [a comprehensive tutorial](https://msberends.github.io/AMR/articles/AMR.html) about how to conduct AMR data analysis, the [complete documentation of all functions](https://msberends.github.io/AMR/reference/) and [an example analysis using WHONET data](https://msberends.github.io/AMR/articles/WHONET.html).
#' All data sets in this `AMR` package (about microorganisms, antibiotics, R/SI interpretation, EUCAST rules, etc.) are publicly and freely available for download in the following formats: R, MS Excel, Apache Feather, Apache Parquet, SPSS, SAS, and Stata. We also provide tab-separated plain text files that are machine-readable and suitable for input in any software program, such as laboratory information systems. 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 Contact Us:
#' For suggestions, comments or questions, please contact us at:
#' For suggestions, comments or questions, please contact us via:
#'
#' Matthijs S. Berends \cr
#' Dr. Matthijs S. Berends \cr
#' m.s.berends \[at\] umcg \[dot\] nl \cr
#' University of Groningen
#' Department of Medical Microbiology and Infection Prevention \cr
+10 -11
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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*
@@ -51,7 +50,7 @@
#'
#' - `"g"` = gram
#' - `"mg"` = milligram
#' - `"mcg"`` = microgram
#' - `"mcg"` = microgram
#' - `"U"` = unit
#' - `"TU"` = thousand units
#' - `"MU"` = million units
@@ -61,7 +60,6 @@
#' **N.B. This function requires an internet connection and only works if the following packages are installed: `curl`, `rvest`, `xml2`.**
#' @export
#' @rdname atc_online
#' @inheritSection AMR Read more on Our Website!
#' @source <https://www.whocc.no/atc_ddd_alterations__cumulative/ddd_alterations/abbrevations/>
#' @examples
#' \donttest{
@@ -105,7 +103,8 @@ atc_online_property <- function(atc_code,
if (!has_internet()) {
message_("There appears to be no internet connection, returning NA.",
add_fn = font_red,
as_note = FALSE)
as_note = FALSE
)
return(rep(NA, length(atc_code)))
}
@@ -126,7 +125,6 @@ atc_online_property <- function(atc_code,
on.exit(close(progress))
for (i in seq_len(length(atc_code))) {
progress$tick()
if (atc_code[i] %like% "^Q") {
@@ -143,7 +141,8 @@ atc_online_property <- function(atc_code,
html_node("#content") %pm>%
html_children() %pm>%
html_node("a"),
error = function(e) NULL)
error = function(e) NULL
)
if (is.null(out)) {
message_("Connection to ", atc_url, " failed.")
return(rep(NA, length(atc_code)))
@@ -158,14 +157,14 @@ atc_online_property <- function(atc_code,
# 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)
error = function(e) NULL
)
if (is.null(out)) {
message_("Connection to ", atc_url, " failed.")
return(rep(NA, length(atc_code)))
@@ -182,15 +181,15 @@ atc_online_property <- function(atc_code,
if (property %in% c("atc", "name")) {
# ATC and name are only in first row
returnvalue[i] <- out[1, property]
returnvalue[i] <- out[1, property, drop = TRUE]
} else {
if (!"adm.r" %in% colnames(out) | is.na(out[1, "adm.r"])) {
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]
returnvalue[i] <- out[j, property, drop = TRUE]
}
}
}
+8 -6
View File
@@ -26,19 +26,17 @@
#' 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()].
#' @inheritSection lifecycle Stable Lifecycle
#' @param tbl a [data.frame] or [list]
#' @param width number of characters to present the visual availability, defaults to 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
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' availability(example_isolates)
#' \donttest{
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter(mo == as.mo("E. coli")) %>%
#' filter(mo == as.mo("Escherichia coli")) %>%
#' select_if(is.rsi) %>%
#' availability()
#' }
@@ -47,6 +45,8 @@ 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)
})
@@ -82,14 +82,16 @@ availability <- function(tbl, width = NULL) {
x_chars <- strrep("#", round(x, digits = 2) / (1 / width))
x_chars_empty <- strrep("-", width - nchar(x_chars))
df <- data.frame(count = n,
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)
stringsAsFactors = FALSE
)
if (length(R[is.na(R)]) == ncol(tbl)) {
df[, 1:3]
df[, 1:3, drop = FALSE]
} else {
df
}
+67 -43
View File
@@ -26,7 +26,6 @@
#' 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*.
#' @inheritSection lifecycle Stable Lifecycle
#' @inheritParams eucast_rules
#' @param combine_IR a [logical] to indicate whether values R and I should be summed
#' @param add_ab_group a [logical] to indicate where the group of the antimicrobials must be included as a first column
@@ -41,21 +40,25 @@
#' @rdname bug_drug_combinations
#' @return The function [bug_drug_combinations()] returns a [data.frame] with columns "mo", "ab", "S", "I", "R" and "total".
#' @source \strong{M39 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 4th Edition}, 2014, *Clinical and Laboratory Standards Institute (CLSI)*. <https://clsi.org/standards/products/microbiology/documents/m39/>.
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \donttest{
#' x <- bug_drug_combinations(example_isolates)
#' x
#' 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)
#' FUN = mo_gramstain
#' )
#'
#' bug_drug_combinations(example_isolates,
#' FUN = function(x) ifelse(x == as.mo("E. coli"),
#' FUN = function(x) {
#' ifelse(x == as.mo("Escherichia coli"),
#' "E. coli",
#' "Others"))
#' "Others"
#' )
#' }
#' )
#' }
bug_drug_combinations <- function(x,
col_mo = NULL,
@@ -91,13 +94,15 @@ bug_drug_combinations <- function(x,
}
run_it <- function(x) {
out <- data.frame(mo = character(0),
out <- data.frame(
mo = character(0),
ab = character(0),
S = integer(0),
I = integer(0),
R = integer(0),
total = integer(0),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
if (data_has_groups) {
group_values <- unique(x[, which(colnames(x) %in% groups), drop = FALSE])
rownames(group_values) <- NULL
@@ -113,18 +118,21 @@ bug_drug_combinations <- function(x,
data.frame(S = m["S", ], I = m["I", ], R = m["R", ], stringsAsFactors = FALSE)
})
merged <- do.call(rbind, pivot)
out_group <- data.frame(mo = rep(unique_mo[i], NROW(merged)),
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)
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))
each = nrow(out_group) / nrow(group_values)
)
group_values <- group_values[repeated, , drop = FALSE]
}
out_group <- cbind(group_values, out_group)
@@ -146,15 +154,12 @@ bug_drug_combinations <- function(x,
if (data_has_groups) {
out <- apply_group(x, "run_it", groups)
rownames(out) <- NULL
set_clean_class(out,
new_class = c("grouped", "bug_drug_combinations", "data.frame"))
} else {
out <- run_it(x)
rownames(out) <- NULL
set_clean_class(out,
new_class = c("bug_drug_combinations", "data.frame"))
}
rownames(out) <- NULL
out <- as_original_data_class(out, class(x.bak))
structure(out, class = c("bug_drug_combinations", ifelse(data_has_groups, "grouped", character(0)), class(out)))
}
#' @method format bug_drug_combinations
@@ -182,19 +187,25 @@ format.bug_drug_combinations <- function(x,
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)),
x <- data.frame(
mo = gsub("(.*)%%(.*)", "\\1", names(idx)),
ab = gsub("(.*)%%(.*)", "\\2", names(idx)),
S = sapply(idx, function(i) sum(y$S[i], na.rm = TRUE)),
I = sapply(idx, function(i) sum(y$I[i], na.rm = TRUE)),
R = sapply(idx, function(i) sum(y$R[i], na.rm = TRUE)),
total = sapply(idx, function(i) sum(y$S[i], na.rm = TRUE) +
sum(y$I[i], na.rm = TRUE) +
sum(y$R[i], na.rm = TRUE)),
stringsAsFactors = FALSE)
S = sapply(idx, function(i) sum(x$S[i], na.rm = TRUE)),
I = sapply(idx, function(i) sum(x$I[i], na.rm = TRUE)),
R = sapply(idx, function(i) sum(x$R[i], na.rm = TRUE)),
total = sapply(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)
@@ -228,7 +239,8 @@ format.bug_drug_combinations <- function(x,
remove_NAs <- function(.data) {
cols <- colnames(.data)
.data <- as.data.frame(lapply(.data, function(x) ifelse(is.na(x), "", x)),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
colnames(.data) <- cols
.data
}
@@ -242,23 +254,29 @@ format.bug_drug_combinations <- function(x,
}
y <- x %pm>%
create_var(ab = as.ab(x$ab),
ab_txt = give_ab_name(ab = x$ab, format = translate_ab, language = language)) %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_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),
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>%
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")]
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>%
@@ -271,7 +289,7 @@ format.bug_drug_combinations <- function(x,
remove_NAs()
select_ab_vars <- function(.data) {
.data[, c("ab_group", "ab_txt", colnames(.data)[!colnames(.data) %in% c("ab_group", "ab_txt", "ab")])]
.data[, c("ab_group", "ab_txt", colnames(.data)[!colnames(.data) %in% c("ab_group", "ab_txt", "ab")]), drop = FALSE]
}
y <- y %pm>%
@@ -285,15 +303,17 @@ format.bug_drug_combinations <- function(x,
y <- y %pm>%
pm_select(-ab_group) %pm>%
pm_rename("Drug" = ab_txt)
colnames(y)[1] <- translate_AMR(colnames(y)[1], language, only_unknown = FALSE)
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)
pm_rename(
"Group" = ab_group,
"Drug" = ab_txt
)
}
if (!is.null(language)) {
colnames(y) <- translate_AMR(colnames(y), language, only_unknown = FALSE)
colnames(y) <- translate_into_language(colnames(y), language, only_unknown = FALSE)
}
if (remove_intrinsic_resistant == TRUE) {
@@ -301,17 +321,21 @@ format.bug_drug_combinations <- function(x,
}
rownames(y) <- NULL
y
as_original_data_class(y, class(x.bak))
}
#' @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")]),
...)
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)
as_note = FALSE
)
}
+30 -30
View File
@@ -49,9 +49,9 @@ format_included_data_number <- function(data) {
#' [Click here][catalogue_of_life] for more information about the included taxa. Check which versions of the CoL and LPSN were included in this package with [catalogue_of_life_version()].
#' @section Included Taxa:
#' Included are:
#' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom %in% c("Archeae", "Bacteria", "Chromista", "Protozoa")), ])` (sub)species from the kingdoms of Archaea, Bacteria, Chromista and Protozoa
#' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Fungi" & microorganisms$order %in% c("Eurotiales", "Microascales", "Mucorales", "Onygenales", "Pneumocystales", "Saccharomycetales", "Schizosaccharomycetales", "Tremellales")), ])` (sub)species from these orders of the kingdom of Fungi: Eurotiales, Microascales, Mucorales, Onygenales, Pneumocystales, Saccharomycetales, Schizosaccharomycetales and Tremellales, as well as `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Fungi" & !microorganisms$order %in% c("Eurotiales", "Microascales", "Mucorales", "Onygenales", "Pneumocystales", "Saccharomycetales", "Schizosaccharomycetales", "Tremellales")), ])` other fungal (sub)species. 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 and including everything would tremendously slow down our algorithms too. By only including the aforementioned taxonomic orders, the most relevant fungi are covered (such as all species of *Aspergillus*, *Candida*, *Cryptococcus*, *Histplasma*, *Pneumocystis*, *Saccharomyces* and *Trichophyton*).
#' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Animalia"), ])` (sub)species from `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Animalia"), "genus"])` other relevant genera from the kingdom of Animalia (such as *Strongyloides* and *Taenia*)
#' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom %in% c("Archeae", "Bacteria", "Chromista", "Protozoa")), , drop = FALSE])` (sub)species from the kingdoms of Archaea, Bacteria, Chromista and Protozoa
#' - All `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Fungi" & microorganisms$order %in% c("Eurotiales", "Microascales", "Mucorales", "Onygenales", "Pneumocystales", "Saccharomycetales", "Schizosaccharomycetales", "Tremellales")), , drop = FALSE])` (sub)species from these orders of the kingdom of Fungi: Eurotiales, Microascales, Mucorales, Onygenales, Pneumocystales, Saccharomycetales, Schizosaccharomycetales and Tremellales, as well as `r format_included_data_number(microorganisms[which(microorganisms$kingdom == "Fungi" & !microorganisms$order %in% c("Eurotiales", "Microascales", "Mucorales", "Onygenales", "Pneumocystales", "Saccharomycetales", "Schizosaccharomycetales", "Tremellales")), ])` other fungal (sub)species. 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 and including everything would tremendously slow down our algorithms too. By only including the aforementioned taxonomic orders, the most relevant fungi are covered (such as all species of *Aspergillus*, *Candida*, *Cryptococcus*, *Histplasma*, *Pneumocystis*, *Saccharomyces* and *Trichophyton*).
#' - All `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.old)` 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 responsible author(s) and year of scientific publication
@@ -59,7 +59,6 @@ format_included_data_number <- function(data) {
#' The Catalogue of Life (<http://www.catalogueoflife.org>) is the most comprehensive and authoritative global index of species currently available. It holds essential information on the names, relationships and distributions of over 1.9 million species. The Catalogue of Life is used to support the major biodiversity and conservation information services such as the Global Biodiversity Information Facility (GBIF), Encyclopedia of Life (EoL) and the International Union for Conservation of Nature Red List. It is recognised by the Convention on Biological Diversity as a significant component of the Global Taxonomy Initiative and a contribution to Target 1 of the Global Strategy for Plant Conservation.
#'
#' 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>.
#' @inheritSection AMR Read more on Our Website!
#' @name catalogue_of_life
#' @rdname catalogue_of_life
#' @seealso Data set [microorganisms] for the actual data. \cr
@@ -71,28 +70,19 @@ format_included_data_number <- function(data) {
#'
#' # Get a note when a species was renamed
#' mo_shortname("Chlamydophila psittaci")
#' # Note: 'Chlamydophila psittaci' (Everett et al., 1999) was renamed back to
#' # 'Chlamydia psittaci' (Page, 1968)
#' #> [1] "C. psittaci"
#'
#' # Get any property from the entire taxonomic tree for all included species
#' mo_class("E. coli")
#' #> [1] "Gammaproteobacteria"
#' mo_class("Escherichia coli")
#'
#' mo_family("E. coli")
#' #> [1] "Enterobacteriaceae"
#' mo_family("Escherichia coli")
#'
#' mo_gramstain("E. coli") # based on kingdom and phylum, see ?mo_gramstain
#' #> [1] "Gram-negative"
#' mo_gramstain("Escherichia coli") # based on kingdom and phylum, see ?mo_gramstain
#'
#' mo_ref("E. coli")
#' #> [1] "Castellani et al., 1919"
#' mo_ref("Escherichia coli")
#'
#' # Do not get mistaken - this package is about microorganisms
#' mo_kingdom("C. elegans")
#' #> [1] "Fungi" # Fungi?!
#' mo_name("C. elegans")
#' #> [1] "Cladosporium elegans" # Because a microorganism was found
NULL
#' Version info of included Catalogue of Life
@@ -102,44 +92,54 @@ NULL
#' @details For LPSN, see [microorganisms].
#' @return a [list], which prints in pretty format
#' @inheritSection catalogue_of_life Catalogue of Life
#' @inheritSection AMR Read more on Our Website!
#' @export
catalogue_of_life_version <- function() {
check_dataset_integrity()
# see the `CATALOGUE_OF_LIFE` list in R/globals.R
lst <- list(CoL =
list(version = gsub("{year}", CATALOGUE_OF_LIFE$year, CATALOGUE_OF_LIFE$version, fixed = TRUE),
lst <- list(
CoL =
list(
version = gsub("{year}", CATALOGUE_OF_LIFE$year, CATALOGUE_OF_LIFE$version, fixed = TRUE),
url = gsub("{year}", CATALOGUE_OF_LIFE$year, CATALOGUE_OF_LIFE$url_CoL, fixed = TRUE),
n = nrow(pm_filter(microorganisms, source == "CoL"))),
n = nrow(pm_filter(microorganisms, source == "CoL"))
),
LPSN =
list(version = "List of Prokaryotic names with Standing in Nomenclature",
list(
version = "List of Prokaryotic names with Standing in Nomenclature",
url = CATALOGUE_OF_LIFE$url_LPSN,
yearmonth = CATALOGUE_OF_LIFE$yearmonth_LPSN,
n = nrow(pm_filter(microorganisms, source == "LPSN"))),
n = nrow(pm_filter(microorganisms, source == "LPSN"))
),
total_included =
list(
n_total_species = nrow(microorganisms),
n_total_synonyms = nrow(microorganisms.old)))
n_total_synonyms = nrow(microorganisms.old)
)
)
set_clean_class(lst,
new_class = c("catalogue_of_life_version", "list"))
new_class = c("catalogue_of_life_version", "list")
)
}
#' @method print catalogue_of_life_version
#' @export
#' @noRd
print.catalogue_of_life_version <- function(x, ...) {
cat(paste0(font_bold("Included in this AMR package (v", utils::packageDescription("AMR")$Version, ") are:\n\n", collapse = ""),
cat(paste0(
font_bold("Included in this AMR package (v", utils::packageDescription("AMR")$Version, ") are:\n\n", collapse = ""),
font_underline(x$CoL$version), "\n",
" Available at: ", font_blue(x$CoL$url), "\n",
" Number of included microbial species: ", format(x$CoL$n, big.mark = ","), "\n",
font_underline(paste0(x$LPSN$version, " (",
x$LPSN$yearmonth, ")")), "\n",
font_underline(paste0(
x$LPSN$version, " (",
x$LPSN$yearmonth, ")"
)), "\n",
" Available at: ", font_blue(x$LPSN$url), "\n",
" Number of included bacterial species: ", format(x$LPSN$n, big.mark = ","), "\n\n",
"=> Total number of species included: ", format(x$total_included$n_total_species, big.mark = ","), "\n",
"=> Total number of synonyms included: ", format(x$total_included$n_total_synonyms, big.mark = ","), "\n\n",
"See for more info ", font_grey_bg("`?microorganisms`"), " and ", font_grey_bg("`?catalogue_of_life`"), ".\n"))
"See for more info ", font_grey_bg("`?microorganisms`"), " and ", font_grey_bg("`?catalogue_of_life`"), ".\n"
))
}
+49 -28
View File
@@ -28,7 +28,6 @@
#' @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.
#' @inheritSection lifecycle Stable Lifecycle
#' @param ... one or more vectors (or columns) with antibiotic interpretations. They will be transformed internally with [as.rsi()] if needed.
#' @inheritParams proportion
#' @inheritSection as.rsi Interpretation of R and S/I
@@ -45,11 +44,11 @@
#' @rdname count
#' @name count
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # example_isolates is a data set available in the AMR package.
#' ?example_isolates
#' # 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"
@@ -72,21 +71,24 @@
#' count_susceptible(example_isolates$AMX)
#' susceptibility(example_isolates$AMX) * n_rsi(example_isolates$AMX)
#'
#' # dplyr -------------------------------------------------------------
#' \donttest{
#' if (require("dplyr")) {
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(R = count_R(CIP),
#' 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_rsi(CIP), # same - analogous to n_distinct
#' total = n()) # NOT the number of tested isolates!
#' 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(hospital_id) %>%
#' group_by(ward) %>%
#' summarise(across(aminoglycosides(), n_rsi))
#'
#' # Count co-resistance between amoxicillin/clav acid and gentamicin,
@@ -108,8 +110,8 @@
#'
#' # It also supports grouping variables
#' example_isolates %>%
#' select(hospital_id, AMX, CIP) %>%
#' group_by(hospital_id) %>%
#' select(ward, AMX, CIP) %>%
#' group_by(ward) %>%
#' count_df(translate = FALSE)
#' }
#' }
@@ -118,8 +120,10 @@ count_resistant <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = "R",
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -129,8 +133,10 @@ count_susceptible <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = c("S", "I"),
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -140,8 +146,10 @@ count_R <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = "R",
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -154,8 +162,10 @@ count_IR <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = c("I", "R"),
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -165,8 +175,10 @@ count_I <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = "I",
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -176,8 +188,10 @@ count_SI <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = c("S", "I"),
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -190,8 +204,10 @@ count_S <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = "S",
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -201,8 +217,10 @@ count_all <- function(..., only_all_tested = FALSE) {
rsi_calc(...,
ab_result = c("S", "I", "R"),
only_all_tested = only_all_tested,
only_count = TRUE),
error = function(e) stop_(e$message, call = -5))
only_count = TRUE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname count
@@ -217,12 +235,15 @@ count_df <- function(data,
combine_SI = TRUE,
combine_IR = FALSE) {
tryCatch(
rsi_calc_df(type = "count",
rsi_calc_df(
type = "count",
data = data,
translate_ab = translate_ab,
language = language,
combine_SI = combine_SI,
combine_IR = combine_IR,
combine_SI_missing = missing(combine_SI)),
error = function(e) stop_(e$message, call = -5))
combine_SI_missing = missing(combine_SI)
),
error = function(e) stop_(e$message, call = -5)
)
}
+65 -57
View File
@@ -26,99 +26,93 @@
#' Define Custom EUCAST Rules
#'
#' Define custom EUCAST rules for your organisation or specific analysis and use the output of this function in [eucast_rules()].
#' @inheritSection lifecycle Stable Lifecycle
#' @param ... rules in formula notation, see *Examples*
#' @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:
#'
#' ```
#' df <- data.frame(mo = c("E. coli", "K. pneumoniae"),
#' TZP = "R",
#' amox = "",
#' AMP = "")
#' ```{r}
#' df <- data.frame(mo = c("Escherichia coli", "Klebsiella pneumoniae"),
#' TZP = as.rsi("R"),
#' ampi = as.rsi("S"),
#' cipro = as.rsi("S"))
#' df
#' #> mo TZP amox AMP
#' #> 1 E. coli R
#' #> 2 K. pneumoniae R
#'
#' eucast_rules(df, rules = "custom", custom_rules = x)
#' #> mo TZP amox AMP
#' #> 1 E. coli R R R
#' #> 2 K. pneumoniae R R R
#' eucast_rules(df, rules = "custom", custom_rules = x, info = FALSE)
#' ```
#'
#' ### Using taxonomic properties in rules
#'
#' There is one exception in variables 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), quote = "``", sort = FALSE)`. Thus, this next example will work as well, despite the fact that the `df` data set does not contain a column `genus`:
#' There is one exception in variables 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)
#' #> mo TZP amox AMP
#' #> 1 E. coli R
#' #> 2 K. pneumoniae R R R
#' eucast_rules(df, rules = "custom", custom_rules = y, info = FALSE)
#' ```
#'
#' ### 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 agents 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 = "")`
#' `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
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' x <- custom_eucast_rules(AMC == "R" & genus == "Klebsiella" ~ aminopenicillins == "R",
#' AMC == "I" & genus == "Klebsiella" ~ aminopenicillins == "I")
#' 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)
#' info = FALSE,
#' verbose = TRUE
#' )
#'
#' # combine rule sets
#' x2 <- c(x,
#' custom_eucast_rules(TZP == "R" ~ carbapenems == "R"))
#' 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`")
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`")
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]]
@@ -137,8 +131,10 @@ custom_eucast_rules <- function(...) {
# 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`")
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'
@@ -150,18 +146,24 @@ custom_eucast_rules <- function(...) {
result_group <- tryCatch(
suppressWarnings(as.ab(result_group,
fast_mode = TRUE,
flag_multiple_results = FALSE)),
error = function(e) NA_character_)
flag_multiple_results = FALSE
)),
error = function(e) NA_character_
)
}
stop_if(any(is.na(result_group)),
stop_if(
any(is.na(result_group)),
"this result of rule ", i, " could not be translated to a single antimicrobial agent/group: \"",
as.character(result)[[2]], "\".\n\nThe input can be a name or code of an antimicrobial agent, or be one of: ",
vector_or(tolower(gsub("AB_", "", DEFINED_AB_GROUPS)), quotes = FALSE), ".")
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("R", "S", "I", NA),
"the resulting value of rule ", i, " must be either \"R\", \"S\", \"I\" or NA")
stop_ifnot(
result_value %in% c("R", "S", "I", NA),
"the resulting value of rule ", i, " must be either \"R\", \"S\", \"I\" or NA"
)
result_value <- as.rsi(result_value)
out[[i]]$result_group <- result_group
@@ -211,13 +213,19 @@ print.custom_eucast_rules <- function(x, ...) {
} else {
val <- font_rsi_I_bg(font_black(" I "))
}
agents <- paste0(font_blue(ab_name(rule$result_group, language = NULL, tolower = TRUE),
collapse = NULL),
" (", rule$result_group, ")")
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 <- 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 = "")
+67 -72
View File
@@ -27,7 +27,7 @@
#'
#' 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 [data.frame] with `r nrow(antibiotics)` observations and `r ncol(antibiotics)` variables:
#' ## 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
#' - `cid`\cr Compound ID as found in PubChem
#' - `name`\cr Official name as used by WHONET/EARS-Net or the WHO
@@ -43,7 +43,7 @@
#' - `iv_units`\cr Units of `iv_ddd`
#' - `loinc`\cr All LOINC codes (Logical Observation Identifiers Names and Codes) associated with the name of the antimicrobial agent. Use [ab_loinc()] to retrieve them quickly, see [ab_property()].
#'
#' ## For the [antivirals] data set: a [data.frame] with `r nrow(antivirals)` observations and `r ncol(antivirals)` variables:
#' ## For the [antivirals] data set: a [tibble][tibble::tibble] with `r nrow(antivirals)` observations and `r ncol(antivirals)` variables:
#' - `atc`\cr ATC codes (Anatomical Therapeutic Chemical) as defined by the WHOCC
#' - `cid`\cr Compound ID as found in PubChem
#' - `name`\cr Official name as used by WHONET/EARS-Net or the WHO
@@ -58,22 +58,15 @@
#' Synonyms (i.e. trade names) were derived from the Compound ID (`cid`) and consequently only available where a CID is available.
#'
#' ## Direct download
#' These data sets are available as 'flat files' for use even without \R - you can find the files here:
#'
#' * <https://github.com/msberends/AMR/raw/main/data-raw/antibiotics.txt>
#' * <https://github.com/msberends/AMR/raw/main/data-raw/antivirals.txt>
#'
#' Files in \R format (with preserved data structure) can be found here:
#'
#' * <https://github.com/msberends/AMR/raw/main/data/antibiotics.rda>
#' * <https://github.com/msberends/AMR/raw/main/data/antivirals.rda>
#' 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/>
#'
#' European Commission Public Health PHARMACEUTICALS - COMMUNITY REGISTER: <https://ec.europa.eu/health/documents/community-register/html/reg_hum_atc.htm>
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection WHOCC WHOCC
#' @inheritSection AMR Read more on Our Website!
#' @seealso [microorganisms], [intrinsic_resistant]
#' @examples
#' antibiotics
#' antivirals
"antibiotics"
#' @rdname antibiotics
@@ -83,7 +76,7 @@
#'
#' A data set containing the full microbial taxonomy (**last updated: `r CATALOGUE_OF_LIFE$yearmonth_LPSN`**) of `r nr2char(length(unique(microorganisms$kingdom[!microorganisms$kingdom %like% "unknown"])))` kingdoms from the Catalogue of Life (CoL) and the List of Prokaryotic names with Standing in Nomenclature (LPSN). MO codes can be looked up using [as.mo()].
#' @inheritSection catalogue_of_life Catalogue of Life
#' @format A [data.frame] with `r format(nrow(microorganisms), big.mark = ",")` observations and `r ncol(microorganisms)` variables:
#' @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
#' - `fullname`\cr Full name, like `"Escherichia coli"`
#' - `kingdom`, `phylum`, `class`, `order`, `family`, `genus`, `species`, `subspecies`\cr Taxonomic rank of the microorganism
@@ -104,6 +97,7 @@
#' - 11 entries of *Streptococcus* (beta-haemolytic: groups A, B, C, D, F, G, H, K and unspecified; other: viridans, milleri)
#' - 2 entries of *Staphylococcus* (coagulase-negative (CoNS) and coagulase-positive (CoPS))
#' - 3 entries of *Trichomonas* (*T. vaginalis*, and its family and genus)
#' - 4 entries of *Toxoplasma* (*T. gondii*, and its order, family and genus)
#' - 1 entry of *Candida* (*C. krusei*), that is not (yet) in the Catalogue of Life
#' - 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
@@ -111,13 +105,7 @@
#' - 6 families under the Enterobacterales order, according to Adeolu *et al.* (2016, PMID 27620848), that are not (yet) in the Catalogue of Life
#'
#' ## Direct download
#' This data set is available as 'flat file' for use even without \R - you can find the file here:
#'
#' * <https://github.com/msberends/AMR/raw/main/data-raw/microorganisms.txt>
#'
#' The file in \R format (with preserved data structure) can be found here:
#'
#' * <https://github.com/msberends/AMR/raw/main/data/microorganisms.rda>
#' 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*):
#' 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.
#'
@@ -137,75 +125,80 @@
#' `r SNOMED_VERSION$current_source` as currently implemented in this `AMR` package:
#'
#' * Retrieved from the `r SNOMED_VERSION$title`, OID `r SNOMED_VERSION$current_oid`, version `r SNOMED_VERSION$current_version`; url: <`r SNOMED_VERSION$url`>
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @seealso [as.mo()], [mo_property()], [microorganisms.codes], [intrinsic_resistant]
#' @examples
#' microorganisms
"microorganisms"
#' Data Set with Previously Accepted Taxonomic Names
#'
#' A data set containing old (previously valid or accepted) taxonomic names according to the Catalogue of Life. This data set is used internally by [as.mo()].
#' @inheritSection catalogue_of_life Catalogue of Life
#' @format A [data.frame] with `r format(nrow(microorganisms.old), big.mark = ",")` observations and `r ncol(microorganisms.old)` variables:
#' @format A [tibble][tibble::tibble] with `r format(nrow(microorganisms.old), big.mark = ",")` observations and `r ncol(microorganisms.old)` variables:
#' - `fullname`\cr Old full taxonomic name of the microorganism
#' - `fullname_new`\cr New full taxonomic name of the microorganism
#' - `ref`\cr Author(s) and year of concerning scientific publication
#' - `prevalence`\cr Prevalence of the microorganism, see [as.mo()]
#' @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).
#' @source Catalogue of Life: Annual Checklist (public online taxonomic database), <http://www.catalogueoflife.org> (check included annual version with [catalogue_of_life_version()]).
#'
#' Parte, A.C. (2018). LPSN - List of Prokaryotic names with Standing in Nomenclature (bacterio.net), 20 years on. International Journal of Systematic and Evolutionary Microbiology, 68, 1825-1829; \doi{10.1099/ijsem.0.002786}
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @seealso [as.mo()] [mo_property()] [microorganisms]
#' @examples
#' microorganisms.old
"microorganisms.old"
#' 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. 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 [data.frame] with `r format(nrow(microorganisms.codes), big.mark = ",")` observations and `r ncol(microorganisms.codes)` variables:
#' @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
#' - `mo`\cr ID of the microorganism in the [microorganisms] data set
#' @inheritSection AMR Reference Data Publicly Available
#' @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).
#' @inheritSection catalogue_of_life Catalogue of Life
#' @inheritSection AMR Read more on Our Website!
#' @seealso [as.mo()] [microorganisms]
#' @examples
#' microorganisms.codes
"microorganisms.codes"
#' 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. The data set reflects reality and can be used to practice AMR data analysis. For examples, please read [the tutorial on our website](https://msberends.github.io/AMR/articles/AMR.html).
#' @format A [data.frame] with `r format(nrow(example_isolates), big.mark = ",")` observations and `r ncol(example_isolates)` variables:
#' - `date`\cr date of receipt at the laboratory
#' - `hospital_id`\cr ID of the hospital, from A to D
#' - `ward_icu`\cr [logical] to determine if ward is an intensive care unit
#' - `ward_clinical`\cr [logical] to determine if ward is a regular clinical ward
#' - `ward_outpatient`\cr [logical] to determine if ward is an outpatient clinic
#' - `age`\cr age of the patient
#' - `gender`\cr gender of the patient
#' - `patient_id`\cr ID of the patient
#' - `mo`\cr ID of microorganism created with [as.mo()], see also [microorganisms]
#' - `PEN:RIF`\cr `r sum(vapply(FUN.VALUE = logical(1), example_isolates, is.rsi))` different antibiotics with class [`rsi`] (see [as.rsi()]); these column names occur in the [antibiotics] data set and can be translated with [ab_name()]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' 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.rsi))` different antibiotics with class [`rsi`] (see [as.rsi()]); 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 [data.frame] with `r format(nrow(example_isolates_unclean), big.mark = ",")` observations and `r ncol(example_isolates_unclean)` variables:
#' @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.rsi()]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @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 are created using online surname generators and are only in place for practice purposes.
#' @format A [data.frame] with `r format(nrow(WHONET), big.mark = ",")` observations and `r ncol(WHONET)` variables:
#' @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()].
@@ -232,14 +225,16 @@
#' - `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.rsi))` 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.rsi()].
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @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 for R/SI Interpretation
#'
#' Data set containing reference data to interpret MIC and disk diffusion to R/SI values, according to international guidelines. Currently implemented guidelines are EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "CLSI")$guideline)))`). Use [as.rsi()] to transform MICs or disks measurements to R/SI values.
#' @format A [data.frame] with `r format(nrow(rsi_translation), big.mark = ",")` observations and `r ncol(rsi_translation)` variables:
#' @format A [tibble][tibble::tibble] with `r format(nrow(rsi_translation), big.mark = ",")` observations and `r ncol(rsi_translation)` variables:
#' - `guideline`\cr Name of the guideline
#' - `method`\cr Either `r vector_or(rsi_translation$method)`
#' - `site`\cr Body site, e.g. "Oral" or "Respiratory"
@@ -251,40 +246,36 @@
#' - `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 The repository of this `AMR` package contains a file comprising this exact data set: <https://github.com/msberends/AMR/blob/main/data-raw/rsi_translation.txt>. This file **allows for machine reading EUCAST and CLSI guidelines**, which is almost impossible with the Excel and PDF files distributed by EUCAST and CLSI. The file is updated automatically and the `mo` and `ab` columns have been transformed to contain the full official names instead of codes.
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @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).
#'
#' 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.
#' @seealso [intrinsic_resistant]
#' @examples
#' rsi_translation
"rsi_translation"
#' Data Set with Bacterial Intrinsic Resistance
#'
#' Data set containing defined intrinsic resistance by EUCAST of all bug-drug combinations.
#' @format A [data.frame] with `r format(nrow(intrinsic_resistant), big.mark = ",")` observations and `r ncol(intrinsic_resistant)` variables:
#' @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 The repository of this `AMR` package contains a file comprising this data set with full taxonomic and antibiotic names: <https://github.com/msberends/AMR/blob/main/data-raw/intrinsic_resistant.txt>. This file **allows for machine reading EUCAST guidelines about intrinsic resistance**, which is almost impossible with the Excel and PDF files distributed by EUCAST. The file is updated automatically.
#'
#' @details
#' This data set is based on `r format_eucast_version_nr(3.3)`.
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#'
#' ## 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
#' \donttest{
#' if (require("dplyr")) {
#' intrinsic_resistant %>%
#' mutate(mo = mo_name(mo),
#' ab = ab_name(mo))
#' filter(ab == "Vancomycin" & mo %like% "Enterococcus") %>%
#' pull(mo)
#' #> [1] "Enterococcus casseliflavus" "Enterococcus gallinarum"
#' }
#' }
#' 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 [data.frame] with `r format(nrow(dosage), big.mark = ",")` observations and `r ncol(dosage)` variables:
#' @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 agent as used by WHONET/EARS-Net or the WHO
#' - `type`\cr Type of the dosage, either `r vector_or(dosage$type)`
@@ -294,7 +285,11 @@
#' - `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
#' @details `r format_eucast_version_nr(11.0)` are based on the dosages in this data set.
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @details
#' This data set is based on `r format_eucast_version_nr(11.0)`.
#'
#' ## 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).
#' @examples
#' dosage
"dosage"
-2
View File
@@ -26,8 +26,6 @@
#' 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).
#' @inheritSection lifecycle Retired Lifecycle
#' @inheritSection AMR Read more on Our Website!
#' @keywords internal
#' @name AMR-deprecated
# @export
+41 -25
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname as.disk
#' @param x vector
#' @param na.rm a [logical] indicating whether missing values should be removed
@@ -35,27 +34,35 @@
#' @aliases disk
#' @export
#' @seealso [as.rsi()]
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \donttest{
#' # transform existing disk zones to the `disk` class
#' df <- data.frame(microorganism = "E. coli",
#' # 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)
#' TOB = 16
#' )
#' df[, 2:5] <- lapply(df[, 2:5], as.disk)
#' # same with dplyr:
#' # df %>% mutate(across(AMP:TOB, 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.rsi
#' as.rsi(x = as.disk(18),
#' as.rsi(
#' x = as.disk(18),
#' mo = "Strep pneu", # `mo` will be coerced with as.mo()
#' ab = "ampicillin", # and `ab` with as.ab()
#' guideline = "EUCAST")
#' guideline = "EUCAST"
#' )
#'
#' as.rsi(df)
#' }
#' # interpret whole data set, pretend to be all from urinary tract infections:
#' as.rsi(df, uti = TRUE)
as.disk <- function(x, na.rm = FALSE) {
meet_criteria(x, allow_class = c("disk", "character", "numeric", "integer"), allow_NA = TRUE)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
@@ -65,6 +72,7 @@ as.disk <- function(x, na.rm = FALSE) {
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
x[trimws(x) == ""] <- NA
x.bak <- x
na_before <- length(x[is.na(x)])
@@ -80,9 +88,12 @@ as.disk <- function(x, na.rm = FALSE) {
gsub(".", "",
reverse(sub(".", "}}tod{{",
reverse(x),
fixed = TRUE)),
fixed = TRUE),
fixed = TRUE)
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))
@@ -100,14 +111,17 @@ as.disk <- function(x, na.rm = FALSE) {
unique() %pm>%
sort() %pm>%
vector_and(quotes = TRUE)
warning_("in `as.disk()`: ", na_after - na_before, " results truncated (",
warning_(
"in `as.disk()`: ", na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid disk zones: ",
list_missing)
list_missing
)
}
}
set_clean_class(as.integer(x),
new_class = c("disk", "integer"))
new_class = c("disk", "integer")
)
}
all_valid_disks <- function(x) {
@@ -115,7 +129,8 @@ all_valid_disks <- function(x) {
return(FALSE)
}
x_disk <- tryCatch(suppressWarnings(as.disk(x[!is.na(x)])),
error = function(e) NA)
error = function(e) NA
)
!any(is.na(x_disk)) && !all(is.na(x))
}
@@ -123,7 +138,8 @@ all_valid_disks <- function(x) {
#' @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"))
new_class = c("disk", "integer")
)
#' @rdname as.disk
#' @export
@@ -214,10 +230,10 @@ rep.disk <- function(x, ...) {
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(.)))
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(.)))
)
}
+60 -40
View File
@@ -26,7 +26,6 @@
#' Determine (New) Episodes for Patients
#'
#' These functions determine which items in a vector can be considered (the start of) a new episode, based on the argument `episode_days`. 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 values `TRUE`/`FALSE` to indicate whether an item in a vector is the start of a new episode.
#' @inheritSection lifecycle Stable Lifecycle
#' @param x vector of dates (class `Date` or `POSIXt`), will be sorted internally to determine episodes
#' @param episode_days required episode length in days, can also be less than a day or `Inf`, see *Details*
#' @param ... ignored, only in place to allow future extensions
@@ -42,76 +41,95 @@
#' @seealso [first_isolate()]
#' @rdname get_episode
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
#' # See ?example_isolates
#' df <- example_isolates[sample(seq_len(2000), size = 200), ]
#'
#' get_episode(example_isolates$date, episode_days = 60) # indices
#' is_new_episode(example_isolates$date, episode_days = 60) # TRUE/FALSE
#' 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
#' example_isolates[which(get_episode(example_isolates$date, 60) == 3), ]
#' 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)
#' 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:
#' example_isolates %>%
#' mutate(condition = sample(x = c("A", "B", "C"),
#' size = 2000,
#' replace = TRUE)) %>%
#' df %>%
#' mutate(condition = sample(
#' x = c("A", "B", "C"),
#' size = 200,
#' replace = TRUE
#' )) %>%
#' group_by(condition) %>%
#' mutate(new_episode = is_new_episode(date, 365))
#'
#' example_isolates %>%
#' group_by(hospital_id, patient_id) %>%
#' mutate(new_episode = is_new_episode(date, 365)) %>%
#' select(patient, date, condition, new_episode)
#' }
#' if (require("dplyr")) {
#' df %>%
#' group_by(ward, patient) %>%
#' transmute(date,
#' patient_id,
#' patient,
#' new_index = get_episode(date, 60),
#' new_logical = is_new_episode(date, 60))
#'
#'
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(patients = n_distinct(patient_id),
#' new_logical = is_new_episode(date, 60)
#' )
#' }
#' 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)))
#'
#' n_episodes_30 = sum(is_new_episode(date, episode_days = 30))
#' )
#' }
#' if (require("dplyr")) {
#'
#' # grouping on patients and microorganisms leads to the same
#' # results as first_isolate() when using 'episode-based':
#' x <- example_isolates %>%
#' filter_first_isolate(include_unknown = TRUE,
#' method = "episode-based")
#' x <- df %>%
#' filter_first_isolate(
#' include_unknown = TRUE,
#' method = "episode-based"
#' )
#'
#' y <- example_isolates %>%
#' group_by(patient_id, mo) %>%
#' filter(is_new_episode(date, 365))
#' y <- df %>%
#' group_by(patient, mo) %>%
#' filter(is_new_episode(date, 365)) %>%
#' ungroup()
#'
#' identical(x$patient_id, y$patient_id)
#' identical(x, y)
#' }
#' if (require("dplyr")) {
#'
#' # but is_new_episode() has a lot more flexibility than first_isolate(),
#' # since you can now group on anything that seems relevant:
#' example_isolates %>%
#' group_by(patient_id, mo, hospital_id, ward_icu) %>%
#' mutate(flag_episode = is_new_episode(date, 365))
#' 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, ...) {
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)
exec_episode(x = x,
exec_episode(
x = x,
type = "sequential",
episode_days = episode_days,
... = ...)
... = ...
)
}
#' @rdname get_episode
@@ -120,10 +138,12 @@ is_new_episode <- function(x, episode_days, ...) {
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)
exec_episode(x = x,
exec_episode(
x = x,
type = "logical",
episode_days = episode_days,
... = ...)
... = ...
)
}
exec_episode <- function(x, type, episode_days, ...) {
+299 -163
View File
@@ -35,11 +35,15 @@ format_eucast_version_nr <- function(version, markdown = TRUE) {
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, ")"))
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, ")"))
txt <- c(txt, paste0(
lst[[version]]$title, " ", lst[[v]]$version_txt,
" (", lst[[v]]$year, ")"
))
}
}
@@ -52,8 +56,7 @@ format_eucast_version_nr <- function(version, markdown = TRUE) {
#' Apply rules for clinical breakpoints and intrinsic resistance as defined by the European Committee on Antimicrobial Susceptibility Testing (EUCAST, <https://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*.
#' @inheritSection lifecycle Stable Lifecycle
#' @param x data with antibiotic columns, such as `amox`, `AMX` and `AMC`
#' @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, defaults to 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, e.g. using `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.
@@ -76,11 +79,11 @@ format_eucast_version_nr <- function(version, markdown = TRUE) {
#'
#' 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)
#' eucast_rules(example_isolates, rules = "custom", custom_rules = x, info = FALSE)
#' ```
#'
#'
@@ -113,15 +116,19 @@ format_eucast_version_nr <- function(version, markdown = TRUE) {
#' - 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
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \donttest{
#' a <- data.frame(mo = c("Staphylococcus aureus",
#' a <- data.frame(
#' mo = c(
#' "Staphylococcus aureus",
#' "Enterococcus faecalis",
#' "Escherichia coli",
#' "Klebsiella pneumoniae",
#' "Pseudomonas aeruginosa"),
#' "Pseudomonas aeruginosa"
#' ),
#' VAN = "-", # Vancomycin
#' AMX = "-", # Amoxicillin
#' COL = "-", # Colistin
@@ -129,35 +136,29 @@ format_eucast_version_nr <- function(version, markdown = TRUE) {
#' CXM = "-", # Cefuroxime
#' PEN = "S", # Benzylpenicillin
#' FOX = "S", # Cefoxitin
#' stringsAsFactors = FALSE)
#' stringsAsFactors = FALSE
#' )
#'
#' a
#' # mo VAN AMX COL CAZ CXM PEN FOX
#' # 1 Staphylococcus aureus - - - - - S S
#' # 2 Enterococcus faecalis - - - - - S S
#' # 3 Escherichia coli - - - - - S S
#' # 4 Klebsiella pneumoniae - - - - - S S
#' # 5 Pseudomonas aeruginosa - - - - - S S
#' head(a)
#'
#'
#' # apply EUCAST rules: some results wil be changed
#' b <- eucast_rules(a)
#'
#' b
#' # mo VAN AMX COL CAZ CXM PEN FOX
#' # 1 Staphylococcus aureus - S R R S S S
#' # 2 Enterococcus faecalis - - R R R S R
#' # 3 Escherichia coli R - - - - R S
#' # 4 Klebsiella pneumoniae R R - - - R S
#' # 5 Pseudomonas aeruginosa R R - - R R R
#' 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(),
@@ -182,7 +183,8 @@ eucast_rules <- function(x,
if ("custom" %in% rules & is.null(custom_rules)) {
warning_("in `eucast_rules()`: no custom rules were set with the `custom_rules` argument",
immediate = TRUE)
immediate = TRUE
)
rules <- rules[rules != "custom"]
if (length(rules) == 0) {
if (info == TRUE) {
@@ -208,9 +210,11 @@ eucast_rules <- function(x,
}
if (interactive() & verbose == TRUE & info == TRUE) {
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.",
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?")
"\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)
@@ -284,8 +288,10 @@ eucast_rules <- function(x,
}
}
cols_ab <- get_column_abx(x = x,
soft_dependencies = c("AMC",
cols_ab <- get_column_abx(
x = x,
soft_dependencies = c(
"AMC",
"AMP",
"AMX",
"CIP",
@@ -299,13 +305,15 @@ eucast_rules <- function(x,
"PIP",
"TCY",
"TIC",
"TOB"),
"TOB"
),
hard_dependencies = NULL,
verbose = verbose,
info = info,
only_rsi_columns = only_rsi_columns,
fn = "eucast_rules",
...)
...
)
if (!"AMP" %in% names(cols_ab) & "AMX" %in% names(cols_ab)) {
# ampicillin column is missing, but amoxicillin is available
@@ -355,13 +363,17 @@ eucast_rules <- function(x,
} 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], "'")
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 ",
paste0(
ab_names[1], " is '", ab_results[1], "' and ",
ab_names[2], " is '", ab_results[2], "' and ",
ab_names[3], " is '", ab_results[3], "'")
ab_names[3], " is '", ab_results[3], "'"
)
}
}
}
@@ -374,7 +386,8 @@ eucast_rules <- function(x,
# Preparing the data ------------------------------------------------------
verbose_info <- data.frame(rowid = character(0),
verbose_info <- data.frame(
rowid = character(0),
col = character(0),
mo_fullname = character(0),
old = as.rsi(character(0)),
@@ -383,20 +396,24 @@ eucast_rules <- function(x,
rule_group = character(0),
rule_name = character(0),
rule_source = character(0),
stringsAsFactors = FALSE)
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),
x$`.rowid` <- vapply(
FUN.VALUE = character(1),
as.list(as.data.frame(t(x[, c(col_mo, cols_ab), drop = FALSE]),
stringsAsFactors = FALSE)),
stringsAsFactors = FALSE
)),
function(x) {
x[is.na(x)] <- "."
paste0(x, collapse = "")
})
}
)
# save original table, with the new .rowid column
x.bak <- x
@@ -419,11 +436,11 @@ eucast_rules <- function(x,
}
if (any(x$genus == "Staphylococcus", na.rm = TRUE)) {
all_staph <- MO_lookup[which(MO_lookup$genus == "Staphylococcus"), ]
all_staph <- MO_lookup[which(MO_lookup$genus == "Staphylococcus"), , drop = FALSE]
all_staph$CNS_CPS <- suppressWarnings(mo_name(all_staph$mo, Becker = "all", language = NULL))
}
if (any(x$genus == "Streptococcus", na.rm = TRUE)) {
all_strep <- MO_lookup[which(MO_lookup$genus == "Streptococcus"), ]
all_strep <- MO_lookup[which(MO_lookup$genus == "Streptococcus"), , drop = FALSE]
all_strep$Lancefield <- suppressWarnings(mo_name(all_strep$mo, Lancefield = TRUE, language = NULL))
}
@@ -435,11 +452,16 @@ eucast_rules <- function(x,
if (info == TRUE) {
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"))))
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(antibiotics, name %like% "/")[, c("ab", "name")]
ab_enzyme <- subset(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 <- antibiotics[match(ab_enzyme$base_name, antibiotics$name), "ab", drop = TRUE]
@@ -453,7 +475,7 @@ eucast_rules <- function(x,
amox$base_name <- ab_name("AMX", language = NULL)
# merge and sort
ab_enzyme <- rbind(ab_enzyme, ampi, amox)
ab_enzyme <- ab_enzyme[order(ab_enzyme$enzyme_name), ]
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
@@ -462,24 +484,31 @@ eucast_rules <- function(x,
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")
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 (info == TRUE) {
cat(word_wrap(rule_current,
width = getOption("width") - 30,
extra_indent = 6))
extra_indent = 6
))
}
run_changes <- edit_rsi(x = x,
run_changes <- edit_rsi(
x = x,
to = "R",
rule = c(rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)),
rule = c(
rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)
),
rows = which(as.rsi_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)
verbose = verbose
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
@@ -495,25 +524,32 @@ eucast_rules <- function(x,
}
# 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")
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 (info == TRUE) {
cat(word_wrap(rule_current,
width = getOption("width") - 30,
extra_indent = 6))
extra_indent = 6
))
}
run_changes <- edit_rsi(x = x,
run_changes <- edit_rsi(
x = x,
to = "S",
rule = c(rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)),
rule = c(
rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)
),
rows = which(as.rsi_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)
verbose = verbose
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
@@ -529,7 +565,6 @@ eucast_rules <- function(x,
}
}
}
} else {
if (info == TRUE) {
cat("\n")
@@ -550,27 +585,33 @@ eucast_rules <- function(x,
# 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/_internals.R
# 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,
eucast_rules_df <- subset(
eucast_rules_df,
reference.rule_group %unlike% "breakpoint" |
(reference.rule_group %like% "breakpoint" & reference.version == version_breakpoints))
(reference.rule_group %like% "breakpoint" & reference.version == version_breakpoints)
)
}
if (any(c("all", "expert") %in% rules)) {
eucast_rules_df <- subset(eucast_rules_df,
eucast_rules_df <- subset(
eucast_rules_df,
reference.rule_group %unlike% "expert" |
(reference.rule_group %like% "expert" & reference.version == version_expertrules))
(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")
eucast_rules_df <- subset(
eucast_rules_df,
reference.rule %unlike% "ampc"
)
} else {
if (isTRUE(ampc_cephalosporin_resistance)) {
ampc_cephalosporin_resistance <- "R"
@@ -580,7 +621,6 @@ eucast_rules <- function(x,
# 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]
@@ -600,10 +640,14 @@ eucast_rules <- function(x,
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]))
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) {
@@ -618,9 +662,12 @@ eucast_rules <- function(x,
# Print EUCAST intro ------------------------------------------------------
if (rule_group_current %unlike% "other" & eucast_notification_shown == FALSE) {
cat(
paste0("\n", font_grey(strrep("-", 0.95 * options()$width)), "\n",
paste0(
"\n", font_grey(strrep("-", 0.95 * options()$width)), "\n",
word_wrap("Rules by the ", font_bold("European Committee on Antimicrobial Susceptibility Testing (EUCAST)")), "\n",
font_blue("https://eucast.org/"), "\n"))
font_blue("https://eucast.org/"), "\n"
)
)
eucast_notification_shown <- TRUE
}
@@ -630,25 +677,36 @@ eucast_rules <- function(x,
cat(font_bold(
ifelse(
rule_group_current %like% "breakpoint",
paste0("\n",
paste0(
"\n",
word_wrap(
breakpoints_info$title, " (",
font_red(paste0(breakpoints_info$version_txt, ", ", breakpoints_info$year)), ")\n")),
font_red(paste0(breakpoints_info$version_txt, ", ", breakpoints_info$year)), ")\n"
)
),
ifelse(
rule_group_current %like% "expert",
paste0("\n",
paste0(
"\n",
word_wrap(
expertrules_info$title, " (",
font_red(paste0(expertrules_info$version_txt, ", ", expertrules_info$year)), ")\n")),
""))), "\n")
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"))
extra_indent = 6
),
type = "ansi"
))
warned <- FALSE
}
}
@@ -661,27 +719,39 @@ eucast_rules <- function(x,
# 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"),
eucast_rules_df[i, "this_value"] <- paste0(
"^(", paste0(all_staph[which(all_staph$CNS_CPS %like% "negative"),
"fullname",
drop = TRUE],
collapse = "|"),
")$")
drop = TRUE
],
collapse = "|"
),
")$"
)
} else {
eucast_rules_df[i, "this_value"] <- paste0("^(", paste0(all_staph[which(all_staph$CNS_CPS %like% "positive"),
eucast_rules_df[i, "this_value"] <- paste0(
"^(", paste0(all_staph[which(all_staph$CNS_CPS %like% "positive"),
"fullname",
drop = TRUE],
collapse = "|"),
")$")
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]"),
eucast_rules_df[i, "this_value"] <- paste0(
"^(", paste0(all_strep[which(all_strep$Lancefield %like% "group [ABCG]"),
"fullname",
drop = TRUE],
collapse = "|"),
")$")
drop = TRUE
],
collapse = "|"
),
")$"
)
like_is_one_of <- "like"
}
@@ -690,10 +760,13 @@ eucast_rules <- function(x,
mo_value <- paste0("^", mo_value, "$")
} else if (like_is_one_of == "one_of") {
# so 'Clostridium, Actinomyces, ...' will turn into '^(Clostridium|Actinomyces|...)$'
mo_value <- paste0("^(",
mo_value <- paste0(
"^(",
paste(trimws(unlist(strsplit(mo_value, ",", fixed = TRUE))),
collapse = "|"),
")$")
collapse = "|"
),
")$"
)
} else if (like_is_one_of != "like") {
stop("invalid value for column 'like.is.one_of'", call. = FALSE)
}
@@ -705,7 +778,8 @@ eucast_rules <- function(x,
if (is.na(source_antibiotics)) {
rows <- tryCatch(which(x[, if_mo_property, drop = TRUE] %like% mo_value),
error = function(e) integer(0))
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) {
@@ -714,14 +788,16 @@ eucast_rules <- function(x,
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.rsi_no_warning(x[, source_antibiotics[1L]]) == source_value[1L]),
error = function(e) integer(0))
rows <- tryCatch(which(x[, if_mo_property, drop = TRUE] %like% mo_value &
as.rsi_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.rsi_no_warning(x[, source_antibiotics[1L]]) == source_value[1L]
& as.rsi_no_warning(x[, source_antibiotics[2L]]) == source_value[2L]),
error = function(e) integer(0))
rows <- tryCatch(which(x[, if_mo_property, drop = TRUE] %like% mo_value &
as.rsi_no_warning(x[, source_antibiotics[1L]]) == source_value[1L] &
as.rsi_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
@@ -739,19 +815,24 @@ eucast_rules <- function(x,
# Apply rule on data ------------------------------------------------------
# this will return the unique number of changes
run_changes <- edit_rsi(x = x,
run_changes <- edit_rsi(
x = x,
to = target_value,
rule = c(rule_text, rule_group_current, rule_current,
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))),
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)
verbose = verbose
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
@@ -777,35 +858,47 @@ eucast_rules <- function(x,
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 <- 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 ",
rule_text <- paste0(
"report as '", target_value, "' when ",
format_custom_query_rule(rule$query, colours = FALSE), ": ",
get_antibiotic_names(cols))
get_antibiotic_names(cols)
)
if (info == TRUE) {
# print rule
cat(italicise_taxonomy(word_wrap(format_custom_query_rule(rule$query, colours = FALSE),
width = getOption("width") - 30,
extra_indent = 6),
type = "ansi"))
extra_indent = 6
),
type = "ansi"
))
warned <- FALSE
}
run_changes <- edit_rsi(x = x,
run_changes <- edit_rsi(
x = x,
to = target_value,
rule = c(rule_text,
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")),
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)
verbose = verbose
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
@@ -828,7 +921,8 @@ eucast_rules <- function(x,
pm_mutate(row = pm_row_number()) %pm>%
pm_select(`.rowid`, row) %pm>%
pm_right_join(verbose_info,
by = c(".rowid" = "rowid")) %pm>%
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>%
@@ -837,7 +931,6 @@ eucast_rules <- function(x,
}
if (info == TRUE) {
if (verbose == TRUE) {
wouldve <- "would have "
} else {
@@ -845,12 +938,16 @@ eucast_rules <- function(x,
}
cat(paste0("\n", font_grey(strrep("-", 0.95 * options()$width)), "\n"))
cat(word_wrap(paste0("The rules ", paste0(wouldve, "affected "),
font_bold(formatnr(pm_n_distinct(verbose_info$row)),
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"),
"rows"
),
", making a total of ",
font_bold(formatnr(nrow(verbose_info)), "edits\n"))))
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()
@@ -861,18 +958,24 @@ eucast_rules <- function(x,
} else {
colour <- font_green # is function
}
cat(colour(paste0("=> ", wouldve, "added ",
cat(colour(paste0(
"=> ", wouldve, "added ",
font_bold(formatnr(verbose_info %pm>%
pm_filter(is.na(old)) %pm>%
nrow()), "test results"),
"\n")))
"\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"))
paste0(
formatnr(added_summary$n), " test result", ifelse(added_summary$n > 1, "s", ""),
" added as ", paste0('"', added_summary$new, '"')
),
collapse = "\n"
))
}
# print changed values
@@ -884,19 +987,25 @@ eucast_rules <- function(x,
if (total_n_added + total_n_changed > 0) {
cat("\n")
}
cat(colour(paste0("=> ", wouldve, "changed ",
cat(colour(paste0(
"=> ", wouldve, "changed ",
font_bold(formatnr(verbose_info %pm>%
pm_filter(!is.na(old)) %pm>%
nrow()), "test results"),
"\n")))
"\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"))
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")
}
@@ -914,17 +1023,20 @@ eucast_rules <- function(x,
# take order from original data set
warn_lacking_rsi_class <- warn_lacking_rsi_class[order(colnames(x.bak))]
warn_lacking_rsi_class <- warn_lacking_rsi_class[!is.na(warn_lacking_rsi_class)]
warning_("in `eucast_rules()`: not all columns with antimicrobial results are of class <rsi>. Transform them on beforehand, with e.g.:\n",
warning_(
"in `eucast_rules()`: not all columns with antimicrobial results are of class <rsi>. Transform them on beforehand, with e.g.:\n",
" - ", x_deparsed, " %>% as.rsi(", ifelse(length(warn_lacking_rsi_class) == 1,
warn_lacking_rsi_class,
paste0(warn_lacking_rsi_class[1], ":", warn_lacking_rsi_class[length(warn_lacking_rsi_class)])), ")\n",
paste0(warn_lacking_rsi_class[1], ":", warn_lacking_rsi_class[length(warn_lacking_rsi_class)])
), ")\n",
" - ", x_deparsed, " %>% mutate_if(is.rsi.eligible, as.rsi)\n",
" - ", x_deparsed, " %>% mutate(across(where(is.rsi.eligible), as.rsi))")
" - ", x_deparsed, " %>% mutate(across(where(is.rsi.eligible), as.rsi))"
)
}
# Return data set ---------------------------------------------------------
if (verbose == TRUE) {
verbose_info
as_original_data_class(verbose_info, old_attributes$class)
} else {
# x was analysed with only unique rows, so join everything together again
x <- x[, c(cols_ab, ".rowid"), drop = FALSE]
@@ -932,7 +1044,7 @@ eucast_rules <- function(x,
x.bak <- x.bak %pm>%
pm_left_join(x, by = ".rowid")
x.bak <- x.bak[, old_cols, drop = FALSE]
# reset original attributes
# reset original attributes, no need for as_original_data_class() here
attributes(x.bak) <- old_attributes
x.bak
}
@@ -952,11 +1064,13 @@ edit_rsi <- function(x,
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,
track_changes <- list(
added = 0,
changed = 0,
output = x,
verbose_info = last_verbose_info,
rsi_warn = character(0))
rsi_warn = character(0)
)
txt_error <- function() {
if (info == TRUE) cat("", font_red_bg(font_white(" ERROR ")), "\n\n")
@@ -979,15 +1093,19 @@ edit_rsi <- function(x,
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)))))
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",
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.")
" because this value was not an existing factor level."
)
txt_warning()
warned <- FALSE
} else {
@@ -997,12 +1115,15 @@ edit_rsi <- function(x,
},
error = function(e) {
txt_error()
stop(paste0("In row(s) ", paste(rows[1:min(length(rows), 10)], collapse = ","),
stop(paste0(
"In row(s) ", paste(rows[1:min(length(rows), 10)], collapse = ","),
ifelse(length(rows) > 10, "...", ""),
" while writing value '", to,
"' to column(s) `", paste(cols, collapse = "`, `"),
"`:\n", e$message),
call. = FALSE)
"`:\n", e$message
),
call. = FALSE
)
}
)
@@ -1012,7 +1133,8 @@ edit_rsi <- function(x,
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],
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],
@@ -1021,14 +1143,18 @@ edit_rsi <- function(x,
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")
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(track_changes$verbose_info,
verbose_new,
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
# count adds and changes
track_changes$added <- track_changes$added + verbose_new %pm>%
pm_filter(is.na(old)) %pm>%
@@ -1055,27 +1181,37 @@ eucast_dosage <- function(ab, administration = "iv", version_breakpoints = 11.0)
# show used version_breakpoints number once per session (pkg_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 ",
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."))
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 = "",
lst[[i]] <- list(
ab = "",
name = "",
standard_dosage = ifelse("standard_dosage" %in% df$type,
df[which(df$type == "standard_dosage"), ]$original_txt,
NA_character_),
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,
NA_character_))
df[which(df$type == "high_dosage"), "original_txt", drop = TRUE],
NA_character_
)
)
}
out <- do.call("rbind", 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", also_load = FALSE)) {
import_fn("as_tibble", "tibble")(out)
} else {
out
}
}
+121 -80
View File
@@ -26,14 +26,13 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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), defaults to the first column with a date class
#' @param col_patient_id column name of the unique IDs of the patients, defaults to the first column that starts with 'patient' or 'patid' (case insensitive)
#' @param col_mo column name of the IDs of the microorganisms (see [as.mo()]), defaults to 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)
#' @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()]. Defaults to 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)
@@ -120,13 +119,12 @@
#' @rdname first_isolate
#' @seealso [key_antimicrobials()]
#' @export
#' @return A [`logical`] vector
#' @return A [logical] vector
#' @source Methodology of this function is strictly based on:
#'
#' - **M39 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 4th Edition**, 2014, *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}
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
@@ -134,38 +132,26 @@
#' example_isolates[first_isolate(), ]
#' \donttest{
#' # get all first Gram-negatives
#' example_isolates[which(first_isolate() & mo_is_gram_negative()), ]
#' 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())
#' }
#' if (require("dplyr")) {
#'
#' # short-hand version:
#' example_isolates %>%
#' filter_first_isolate()
#' filter_first_isolate(info = FALSE)
#' }
#' if (require("dplyr")) {
#'
#' # grouped determination of first isolates (also prints group names):
#' # flag the first isolates per group:
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' mutate(first = first_isolate())
#'
#' # now let's see if first isolates matter:
#' A <- example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(count = n_rsi(GEN), # gentamicin availability
#' resistance = resistance(GEN)) # gentamicin resistance
#'
#' B <- example_isolates %>%
#' filter_first_isolate() %>% # the 1st isolate filter
#' group_by(hospital_id) %>%
#' summarise(count = n_rsi(GEN), # gentamicin availability
#' resistance = resistance(GEN)) # gentamicin resistance
#'
#' # Have a look at A and B.
#' # B is more reliable because every isolate is counted only once.
#' # Gentamicin resistance in hospital D appears to be 4.2% higher than
#' # when you (erroneously) would have used all isolates for analysis.
#' group_by(ward) %>%
#' mutate(first = first_isolate()) %>%
#' select(ward, date, patient, mo, first)
#' }
#' }
first_isolate <- function(x = NULL,
@@ -188,7 +174,6 @@ first_isolate <- function(x = NULL,
include_unknown = FALSE,
include_untested_rsi = TRUE,
...) {
dots <- unlist(list(...))
if (length(dots) != 0) {
# backwards compatibility with old arguments
@@ -215,7 +200,15 @@ first_isolate <- function(x = NULL,
col_specimen <- NULL
}
meet_criteria(col_specimen, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_icu, 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_NULL = TRUE)
if (length(col_icu) == 1) {
col_icu <- rep(col_icu, nrow(x))
}
} else {
meet_criteria(col_icu, allow_class = c("character", "logical"), has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
col_icu <- x[, col_icu, drop = TRUE]
}
# 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"))
@@ -248,23 +241,30 @@ first_isolate <- function(x = NULL,
# remove data.table, grouping from tibbles, etc.
x <- as.data.frame(x, stringsAsFactors = FALSE)
any_col_contains_rsi <- any(vapply(FUN.VALUE = logical(1),
any_col_contains_rsi <- 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("R", "S", "I"), na.rm = TRUE),
USE.NAMES = FALSE))
USE.NAMES = FALSE
))
if (method == "phenotype-based" & !any_col_contains_rsi) {
method <- "episode-based"
}
if (info == TRUE & message_not_thrown_before("first_isolate", "method")) {
message_(paste0("Determining first isolates ",
message_(paste0(
"Determining first isolates ",
ifelse(method %in% c("episode-based", "phenotype-based"),
ifelse(is.infinite(episode_days),
"without a specified episode length",
paste("using an episode length of", episode_days, "days")),
"")),
paste("using an episode length of", episode_days, "days")
),
""
)
),
as_note = FALSE,
add_fn = font_black)
add_fn = font_black
)
}
# try to find columns based on type
@@ -333,7 +333,9 @@ first_isolate <- function(x = NULL,
check_columns_existance <- function(column, tblname = x) {
if (!is.null(column)) {
stop_ifnot(column %in% colnames(tblname),
"Column '", column, "' not found.", call = FALSE)
"Column '", column, "' not found.",
call = FALSE
)
}
}
@@ -341,7 +343,6 @@ first_isolate <- function(x = NULL,
check_columns_existance(col_patient_id)
check_columns_existance(col_mo)
check_columns_existance(col_testcode)
check_columns_existance(col_icu)
check_columns_existance(col_keyantimicrobials)
# convert dates to Date
@@ -363,7 +364,8 @@ first_isolate <- function(x = NULL,
if (!is.null(testcodes_exclude) & info == TRUE & message_not_thrown_before("first_isolate", "excludingtestcodes")) {
message_("Excluding test codes: ", vector_and(testcodes_exclude, quotes = TRUE),
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
if (is.null(col_specimen)) {
@@ -376,7 +378,8 @@ first_isolate <- function(x = NULL,
if (info == TRUE & message_not_thrown_before("first_isolate", "excludingspecimen")) {
message_("Excluding other than specimen group '", specimen_group, "'",
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
}
if (!is.null(col_keyantimicrobials)) {
@@ -389,18 +392,22 @@ first_isolate <- function(x = NULL,
# arrange data to the right sorting
if (is.null(specimen_group)) {
x <- x[order(x$newvar_patient_id,
x <- x[order(
x$newvar_patient_id,
x$newvar_genus_species,
x$newvar_date), ]
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 <- x[order(
pm_pull(x, col_specimen),
x$newvar_patient_id,
x$newvar_genus_species,
x$newvar_date), ]
x$newvar_date
), ]
rownames(x) <- NULL
suppressWarnings(
row.start <- which(x %pm>% pm_pull(col_specimen) == specimen_group) %pm>% min(na.rm = TRUE)
@@ -415,7 +422,8 @@ first_isolate <- function(x = NULL,
if (info == TRUE) {
message_("=> Found ", font_bold("no isolates"),
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
return(rep(FALSE, nrow(x)))
}
@@ -423,7 +431,8 @@ first_isolate <- function(x = NULL,
if (info == TRUE) {
message_("=> Found ", font_bold("1 first isolate"), ", as the data only contained 1 row",
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
return(TRUE)
}
@@ -432,7 +441,8 @@ first_isolate <- function(x = NULL,
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)
as_note = FALSE
)
}
return(rep(TRUE, length(c(row.start:row.end))))
}
@@ -451,13 +461,15 @@ first_isolate <- function(x = NULL,
ifelse(ignore_I == FALSE, "not ", ""),
"ignoring I",
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
if (type == "points") {
message_("Basing inclusion on all antimicrobial results, using a points threshold of ",
points_threshold,
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
}
}
@@ -465,37 +477,48 @@ first_isolate <- function(x = NULL,
x$other_pat_or_mo <- ifelse(x$newvar_patient_id == pm_lag(x$newvar_patient_id) &
x$newvar_genus_species == pm_lag(x$newvar_genus_species),
FALSE,
TRUE)
TRUE
)
x$episode_group <- paste(x$newvar_patient_id, x$newvar_genus_species)
x$more_than_episode_ago <- unlist(lapply(split(x$newvar_date,
x$episode_group),
x$more_than_episode_ago <- unlist(lapply(split(
x$newvar_date,
x$episode_group
),
exec_episode, # this will skip meet_criteria() in is_new_episode(), saving time
type = "logical",
episode_days = episode_days),
use.names = FALSE)
episode_days = episode_days
),
use.names = FALSE
)
if (!is.null(col_keyantimicrobials)) {
# with key antibiotics
x$other_key_ab <- !antimicrobials_equal(y = x$newvar_key_ab,
x$other_key_ab <- !antimicrobials_equal(
y = x$newvar_key_ab,
z = pm_lag(x$newvar_key_ab),
type = type,
ignore_I = ignore_I,
points_threshold = points_threshold)
x$newvar_first_isolate <- pm_if_else(x$newvar_row_index_sorted >= row.start &
points_threshold = points_threshold
)
x$newvar_first_isolate <- pm_if_else(
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$other_key_ab),
TRUE,
FALSE)
FALSE
)
} else {
# no key antibiotics
x$newvar_first_isolate <- pm_if_else(x$newvar_row_index_sorted >= row.start &
x$newvar_first_isolate <- pm_if_else(
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),
TRUE,
FALSE)
FALSE
)
}
# first one as TRUE
@@ -506,14 +529,16 @@ first_isolate <- function(x = NULL,
}
if (!is.null(col_icu)) {
if (icu_exclude == TRUE) {
message_("Excluding isolates from ICU.",
message_("Excluding ", format(sum(col_icu, na.rm = TRUE), big.mark = ","), " isolates from ICU.",
add_fn = font_black,
as_note = FALSE)
x[which(as.logical(x[, col_icu, drop = TRUE])), "newvar_first_isolate"] <- FALSE
as_note = FALSE
)
x[which(col_icu), "newvar_first_isolate"] <- FALSE
} else {
message_("Including isolates from ICU.",
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
}
@@ -538,33 +563,42 @@ first_isolate <- function(x = NULL,
})
message_("\nGroup: ", paste0(names(group), " = ", group, collapse = ", "), "\n",
as_note = FALSE,
add_fn = font_red)
add_fn = font_red
)
}
}
}
# handle empty microorganisms
if (any(x$newvar_mo == "UNKNOWN", na.rm = TRUE) & info == TRUE) {
message_(ifelse(include_unknown == TRUE, "Included ", "Excluded "),
message_(
ifelse(include_unknown == TRUE, "Included ", "Excluded "),
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), "')")
decimal.mark = decimal.mark, big.mark = big.mark
),
" isolates with a microbial ID 'UNKNOWN' (in column '", font_bold(col_mo), "')"
)
}
x[which(x$newvar_mo == "UNKNOWN"), "newvar_first_isolate"] <- include_unknown
# exclude all NAs
if (any(is.na(x$newvar_mo)) & info == TRUE) {
message_("Excluded ", 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), "')")
message_(
"Excluded ", 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), "')"
)
}
x[which(is.na(x$newvar_mo)), "newvar_first_isolate"] <- FALSE
# handle isolates without antibiogram
if (include_untested_rsi == FALSE && any(is.rsi(x))) {
rsi_all_NA <- which(unname(vapply(FUN.VALUE = logical(1),
rsi_all_NA <- which(unname(vapply(
FUN.VALUE = logical(1),
as.data.frame(t(x[, is.rsi(x), drop = FALSE])),
function(rsi_values) all(is.na(rsi_values)))))
function(rsi_values) all(is.na(rsi_values))
)))
x[rsi_all_NA, "newvar_first_isolate"] <- FALSE
}
@@ -584,20 +618,25 @@ first_isolate <- function(x = NULL,
}
# 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,
message_(paste0(
"=> Found ",
font_bold(paste0(
n_found,
ifelse(method == "isolate-based", "", paste0(" '", method, "'")),
" first isolates")),
" 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)
""
),
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
@@ -622,13 +661,15 @@ filter_first_isolate <- function(x = NULL,
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,
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) {
+49 -34
View File
@@ -26,7 +26,6 @@
#' *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**).
#' @inheritSection lifecycle Questioning Lifecycle
#' @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.
#'
@@ -76,7 +75,6 @@
#' - The possibility to simulate p values with `simulate.p.value` was removed
#' @export
#' @importFrom stats pchisq complete.cases
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # = EXAMPLE 1 =
#' # Shivrain et al. (2006) crossed clearfield rice (which are resistant
@@ -88,8 +86,7 @@
#' # ratio.
#'
#' x <- c(772, 1611, 737)
#' G <- g.test(x, p = c(1, 2, 1) / 4)
#' # G$p.value = 0.12574.
#' 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
@@ -105,85 +102,101 @@
#'
#' x <- c(1752, 1895)
#' g.test(x)
#' # p = 0.01787343
#'
#' # 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))
if (is.data.frame(x)) {
x <- as.matrix(x)
}
if (is.matrix(x)) {
if (min(dim(x)) == 1L)
if (min(dim(x)) == 1L) {
x <- as.vector(x)
}
}
if (!is.matrix(x) && !is.null(y)) {
if (length(x) != length(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)
30) {
""
else DNAME
} else {
DNAME
}
yname <- if (length(DNAME2) > 1L || nchar(DNAME2, "w") >
30)
30) {
""
else DNAME2
} else {
DNAME2
}
OK <- complete.cases(x, y)
x <- factor(x[OK])
y <- factor(y[OK])
if ((nlevels(x) < 2L) || (nlevels(y) < 2L))
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"))
DNAME <- paste(
paste(DNAME, collapse = "\n"), "and",
paste(DNAME2, collapse = "\n")
)
}
if (any(x < 0) || any(is.na((x)))) # this last one was anyNA, but only introduced in R 3.1.0
if (any(x < 0) || any(is.na((x)))) { # this last one was anyNA, but only introduced in R 3.1.0
stop("all entries of 'x' must be nonnegative and finite")
if ((n <- sum(x)) == 0)
}
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))
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)
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 <- 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)) # 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)
} else {
if (length(dim(x)) > 2L) {
stop("invalid 'x'")
if (length(x) == 1L)
}
if (length(x) == 1L) {
stop("'x' must at least have 2 elements")
if (length(x) != length(p))
}
if (length(x) != length(p)) {
stop("'x' and 'p' must have the same number of elements")
if (any(p < 0))
}
if (any(p < 0)) {
stop("probabilities must be non-negative.")
}
if (abs(sum(p) - 1) > sqrt(.Machine$double.eps)) {
if (rescale.p)
if (rescale.p) {
p <- p / sum(p)
else stop("probabilities must sum to 1.")
} else {
stop("probabilities must sum to 1.")
}
}
METHOD <- "G-test of goodness-of-fit (likelihood ratio test)"
E <- n * p
@@ -193,15 +206,17 @@ g.test <- function(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))
if (any(E < 5) && is.finite(PARAMETER)) {
warning("G-statistic approximation may be incorrect due to E < 5")
}
structure(list(statistic = STATISTIC, argument = PARAMETER,
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")
stdres = (x - E) / sqrt(V)
), class = "htest")
}
+106 -60
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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()].
@@ -64,23 +63,30 @@
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
#'
#' # See ?pca for more info about Principal Component Analysis (PCA).
#' \donttest{
#' if (require("dplyr")) {
#' pca_model <- example_isolates %>%
#' filter(mo_genus(mo) == "Staphylococcus") %>%
#' group_by(species = mo_shortname(mo)) %>%
#' summarise_if (is.rsi, resistance) %>%
#' pca(FLC, AMC, CXM, GEN, TOB, TMP, SXT, CIP, TEC, TCY, ERY)
#' # 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.rsi, resistance) # then get resistance of all drugs
#'
#' # old (base R)
#' biplot(pca_model)
#' # now conduct PCA for certain antimicrobial agents
#' pca_result <- resistance_data %>%
#' pca(AMC, CXM, CTX, CAZ, GEN, TOB, TMP, SXT)
#'
#' # new
#' ggplot_pca(pca_model)
#' summary(pca_result)
#'
#' # old base R plotting method:
#' biplot(pca_result)
#' # new ggplot2 plotting method using this package:
#' ggplot_pca(pca_result)
#'
#' if (require("ggplot2")) {
#' ggplot_pca(pca_model) +
#' ggplot_pca(pca_result) +
#' scale_colour_viridis_d() +
#' labs(title = "Title here")
#' }
@@ -108,7 +114,6 @@ ggplot_pca <- function(x,
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)
@@ -132,7 +137,8 @@ ggplot_pca <- function(x,
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,
calculations <- pca_calculations(
pca_model = x,
groups = groups,
groups_missing = missing(groups),
labels = labels,
@@ -141,7 +147,8 @@ ggplot_pca <- function(x,
scale = scale,
pc.biplot = pc.biplot,
ellipse_prob = ellipse_prob,
labels_text_placement = labels_text_placement)
labels_text_placement = labels_text_placement
)
choices <- calculations$choices
df.u <- calculations$df.u
df.v <- calculations$df.v
@@ -156,10 +163,14 @@ ggplot_pca <- function(x,
} 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)),
")"))
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)) {
@@ -172,87 +183,113 @@ ggplot_pca <- function(x,
}
# Base plot
g <- ggplot2::ggplot(data = df.u,
ggplot2::aes(x = xvar, y = yvar)) +
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))
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) +
size = points_size
) +
ggplot2::geom_text(ggplot2::aes(label = labels, colour = groups),
nudge_y = -0.05,
size = labels_textsize) +
size = labels_textsize
) +
ggplot2::labs(colour = group_name)
} else {
g <- g + ggplot2::geom_point(alpha = points_alpha,
size = points_size) +
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)
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) +
size = points_size
) +
ggplot2::labs(colour = group_name)
} else {
g <- g + ggplot2::geom_point(alpha = points_alpha,
size = points_size)
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,
g <- g + ggplot2::geom_path(
data = ell,
ggplot2::aes(colour = groups, group = groups),
size = ellipse_size,
alpha = points_alpha)
alpha = points_alpha
)
}
# Label the variable axes
if (arrows == TRUE) {
g <- g + ggplot2::geom_segment(data = df.v,
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"),
arrow = ggplot2::arrow(
length = ggplot2::unit(0.5, "picas"),
angle = 20,
ends = "last",
type = "open"),
type = "open"
),
colour = arrows_colour,
size = arrows_size,
alpha = arrows_alpha)
alpha = arrows_alpha
)
if (arrows_textangled == TRUE) {
g <- g + ggplot2::geom_text(data = df.v,
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)
alpha = arrows_alpha
)
} else {
g <- g + ggplot2::geom_text(data = df.v,
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)
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)))))
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"),
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))
plot.subtitle = ggplot2::element_text(hjust = 0.5)
)
g
}
@@ -268,17 +305,19 @@ pca_calculations <- function(pca_model,
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)
error = function(e) NULL
)
group_name <- tryCatch(colnames(non_numeric_cols[1]),
error = function(e) NULL)
error = function(e) NULL
)
}
if (labels_missing) {
labels <- tryCatch(non_numeric_cols[[2]],
error = function(e) NULL)
error = function(e) NULL
)
}
if (!is.null(groups) & is.null(labels)) {
# turn them around
@@ -315,13 +354,15 @@ pca_calculations <- function(pca_model,
# 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)
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 = "*")
v <- sweep(v, 2, d^as.integer(scale), FUN = "*")
df.v <- as.data.frame(v[, choices],
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
names(df.u) <- c("xvar", "yvar")
names(df.v) <- names(df.u)
@@ -333,10 +374,10 @@ pca_calculations <- function(pca_model,
# 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)
r <- sqrt(qchisq(circle_prob, df = 2)) * prod(colMeans(df.u^2))^(0.25)
# Scale directions
v.scale <- rowSums(v ^ 2)
v.scale <- rowSums(v^2)
df.v <- r * df.v / sqrt(max(v.scale))
# Grouping variable
@@ -357,10 +398,12 @@ pca_calculations <- function(pca_model,
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),
return(data.frame(
X1 = numeric(0),
X2 = numeric(0),
groups = character(0),
stringsAsFactors = FALSE))
stringsAsFactors = FALSE
))
}
sigma <- var(cbind(x$xvar, x$yvar))
mu <- c(mean(x$xvar), mean(x$yvar))
@@ -368,9 +411,11 @@ pca_calculations <- function(pca_model,
data.frame(sweep(circle %*% chol(sigma) * ed,
MARGIN = 2,
STATS = mu,
FUN = "+"),
FUN = "+"
),
groups = x$groups[1],
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
})
ell <- do.call(rbind, df.groups)
if (NROW(ell) == 0) {
@@ -382,7 +427,8 @@ pca_calculations <- function(pca_model,
ell <- NULL
}
list(choices = choices,
list(
choices = choices,
df.u = df.u,
df.v = df.v,
ell = ell,
+105 -47
View File
@@ -26,7 +26,6 @@
#' AMR Plots with `ggplot2`
#'
#' Use these functions to create bar plots for AMR data analysis. All functions rely on [ggplot2][ggplot2::ggplot()] functions.
#' @inheritSection lifecycle Stable Lifecycle
#' @param data a [data.frame] with column(s) of class [`rsi`] (see [as.rsi()])
#' @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
@@ -65,14 +64,15 @@
#' [ggplot_rsi()] 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_rsi
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \donttest{
#' if (require("ggplot2") & require("dplyr")) {
#' if (require("ggplot2") && require("dplyr")) {
#'
#' # get antimicrobial results for drugs against a UTI:
#' ggplot(example_isolates %>% select(AMX, NIT, FOS, TMP, CIP)) +
#' geom_rsi()
#' }
#' if (require("ggplot2") && require("dplyr")) {
#'
#' # prettify the plot using some additional functions:
#' df <- example_isolates %>% select(AMX, NIT, FOS, TMP, CIP)
@@ -82,68 +82,91 @@
#' scale_rsi_colours() +
#' labels_rsi_count() +
#' theme_rsi()
#' }
#' 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_rsi()
#' }
#' if (require("ggplot2") && require("dplyr")) {
#'
#' # get only proportions and no counts:
#' example_isolates %>%
#' select(AMX, NIT, FOS, TMP, CIP) %>%
#' ggplot_rsi(datalabels = FALSE)
#' }
#' if (require("ggplot2") && require("dplyr")) {
#'
#' # add other ggplot2 arguments as you like:
#' example_isolates %>%
#' select(AMX, NIT, FOS, TMP, CIP) %>%
#' ggplot_rsi(width = 0.5,
#' ggplot_rsi(
#' width = 0.5,
#' colour = "black",
#' size = 1,
#' linetype = 2,
#' alpha = 0.25)
#' alpha = 0.25
#' )
#' }
#' if (require("ggplot2") && require("dplyr")) {
#'
#' # you can alter the colours with colour names:
#' example_isolates %>%
#' select(AMX) %>%
#' ggplot_rsi(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"),
#' data.frame(
#' x = c("Value1", "Value2", "Value3"),
#' y = c(1, 2, 3),
#' z = c("Value4", "Value5", "Value6")) %>%
#' z = c("Value4", "Value5", "Value6")
#' ) %>%
#' ggplot() +
#' geom_col(aes(x = x, y = y, fill = z)) +
#' scale_rsi_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("E. coli")) %>%
#' 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_rsi(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_rsi(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()) %>%
#' filter(mo_is_gram_negative(), ward != "Outpatient") %>%
#' # select only UTI-specific drugs
#' select(hospital_id, AMX, NIT, FOS, TMP, CIP) %>%
#' group_by(hospital_id) %>%
#' ggplot_rsi(x = "hospital_id",
#' select(ward, AMX, NIT, FOS, TMP, CIP) %>%
#' group_by(ward) %>%
#' ggplot_rsi(
#' x = "ward",
#' facet = "antibiotic",
#' nrow = 1,
#' title = "AMR of Anti-UTI Drugs Per Hospital",
#' x.title = "Hospital",
#' datalabels = FALSE)
#' title = "AMR of Anti-UTI Drugs Per Ward",
#' x.title = "Ward",
#' datalabels = FALSE
#' )
#' }
#' }
ggplot_rsi <- function(data,
@@ -160,11 +183,13 @@ ggplot_rsi <- function(data,
minimum = 30,
language = get_AMR_locale(),
nrow = NULL,
colours = c(S = "#3CAEA3",
colours = c(
S = "#3CAEA3",
SI = "#3CAEA3",
I = "#F6D55C",
IR = "#ED553B",
R = "#ED553B"),
R = "#ED553B"
),
datalabels = TRUE,
datalabels.size = 2.5,
datalabels.colour = "grey15",
@@ -174,7 +199,6 @@ ggplot_rsi <- function(data,
x.title = "Antimicrobial",
y.title = "Proportion",
...) {
stop_ifnot_installed("ggplot2")
meet_criteria(data, allow_class = "data.frame", contains_column_class = "rsi")
meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE)
@@ -223,9 +247,11 @@ ggplot_rsi <- function(data,
}
p <- ggplot2::ggplot(data = data) +
geom_rsi(position = position, x = x, fill = fill, translate_ab = translate_ab,
geom_rsi(
position = position, x = x, fill = fill, translate_ab = translate_ab,
minimum = minimum, language = language,
combine_SI = combine_SI, combine_IR = combine_IR, ...) +
combine_SI = combine_SI, combine_IR = combine_IR, ...
) +
theme_rsi()
if (fill == "interpretation") {
@@ -238,7 +264,8 @@ ggplot_rsi <- function(data,
}
if (datalabels == TRUE) {
p <- p + labels_rsi_count(position = position,
p <- p + labels_rsi_count(
position = position,
x = x,
translate_ab = translate_ab,
minimum = minimum,
@@ -246,18 +273,21 @@ ggplot_rsi <- function(data,
combine_SI = combine_SI,
combine_IR = combine_IR,
datalabels.size = datalabels.size,
datalabels.colour = datalabels.colour)
datalabels.colour = datalabels.colour
)
}
if (!is.null(facet)) {
p <- p + facet_rsi(facet = facet, nrow = nrow)
}
p <- p + ggplot2::labs(title = title,
p <- p + ggplot2::labs(
title = title,
subtitle = subtitle,
caption = caption,
x = x.title,
y = y.title)
y = y.title
)
p
}
@@ -311,12 +341,14 @@ geom_rsi <- function(position = NULL,
ggplot2::geom_col(
data = function(x) {
rsi_df(data = x,
rsi_df(
data = x,
translate_ab = translate_ab,
language = language,
minimum = minimum,
combine_SI = combine_SI,
combine_IR = combine_IR)
combine_IR = combine_IR
)
},
mapping = ggplot2::aes_string(x = x, y = y, fill = fill),
position = position,
@@ -360,9 +392,11 @@ scale_y_percent <- function(breaks = seq(0, 1, 0.1), limits = NULL) {
if (all(breaks[breaks != 0] > 1)) {
breaks <- breaks / 100
}
ggplot2::scale_y_continuous(breaks = breaks,
ggplot2::scale_y_continuous(
breaks = breaks,
labels = percentage(breaks),
limits = limits)
limits = limits
)
}
#' @rdname ggplot_rsi
@@ -373,11 +407,13 @@ scale_rsi_colours <- function(...,
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_rsi()
if ("colours" %in% names(list(...))) {
original_cols <- c(S = "#3CAEA3",
original_cols <- c(
S = "#3CAEA3",
SI = "#3CAEA3",
I = "#F6D55C",
IR = "#ED553B",
R = "#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
@@ -387,18 +423,32 @@ scale_rsi_colours <- function(...,
return(invisible())
}
names_susceptible <- c("S", "SI", "IS", "S+I", "I+S", "susceptible", "Susceptible",
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",
"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]),
"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",
"replacement",
drop = TRUE
])
)
names_resistant <- c(
"R", "IR", "RI", "R+I", "I+R", "resistant", "Resistant",
unique(TRANSLATIONS[which(TRANSLATIONS$pattern == "Resistant"),
"replacement", drop = TRUE]))
"replacement",
drop = TRUE
])
)
susceptible <- rep("#3CAEA3", length(names_susceptible))
names(susceptible) <- names_susceptible
@@ -407,7 +457,7 @@ scale_rsi_colours <- function(...,
resistant <- rep("#ED553B", length(names_resistant))
names(resistant) <- names_resistant
original_cols = c(susceptible, incr_exposure, resistant)
original_cols <- c(susceptible, incr_exposure, resistant)
dots <- c(...)
# replace S, I, R as colours: scale_rsi_colours(mydatavalue = "S")
dots[dots == "S"] <- "#3CAEA3"
@@ -424,12 +474,14 @@ scale_rsi_colours <- function(...,
theme_rsi <- function() {
stop_ifnot_installed("ggplot2")
ggplot2::theme_minimal(base_size = 10) +
ggplot2::theme(panel.grid.major.x = ggplot2::element_blank(),
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))
plot.subtitle = ggplot2::element_text(hjust = 0.5)
)
}
#' @rdname ggplot_rsi
@@ -461,26 +513,32 @@ labels_rsi_count <- function(position = NULL,
position <- ggplot2::position_fill(vjust = 0.5, reverse = TRUE)
}
x_name <- x
ggplot2::geom_text(mapping = ggplot2::aes_string(label = "lbl",
ggplot2::geom_text(
mapping = ggplot2::aes_string(
label = "lbl",
x = x,
y = "value"),
y = "value"
),
position = position,
inherit.aes = FALSE,
size = datalabels.size,
colour = datalabels.colour,
lineheight = 0.75,
data = function(x) {
transformed <- rsi_df(data = x,
transformed <- rsi_df(
data = x,
translate_ab = translate_ab,
combine_SI = combine_SI,
combine_IR = combine_IR,
minimum = minimum,
language = language)
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)
})
}
)
}
+67 -48
View File
@@ -26,43 +26,33 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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_rsi_columns a [logical] to indicate whether only antibiotic columns must be detected that were transformed to class `<rsi>` (see [as.rsi()]) on beforehand (defaults to `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. **Longer columns names take precedence over shorter column names.**
#' @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
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' df <- data.frame(amox = "S",
#' tetr = "R")
#' df <- data.frame(
#' amox = "S",
#' tetr = "R"
#' )
#'
#' guess_ab_col(df, "amoxicillin")
#' # [1] "amox"
#' guess_ab_col(df, "J01AA07") # ATC code of tetracycline
#' # [1] "tetr"
#'
#' guess_ab_col(df, "J01AA07", verbose = TRUE)
#' # NOTE: Using column 'tetr' as input for J01AA07 (tetracycline).
#' # [1] "tetr"
#'
#' # WHONET codes
#' df <- data.frame(AMP_ND10 = "R",
#' AMC_ED20 = "S")
#' df <- data.frame(
#' AMP_ND10 = "R",
#' AMC_ED20 = "S"
#' )
#' guess_ab_col(df, "ampicillin")
#' # [1] "AMP_ND10"
#' guess_ab_col(df, "J01CR02")
#' # [1] "AMC_ED20"
#' guess_ab_col(df, as.ab("augmentin"))
#' # [1] "AMC_ED20"
#'
#' # Longer names take precendence:
#' df <- data.frame(AMP_ED2 = "S",
#' AMP_ED20 = "S")
#' guess_ab_col(df, "ampicillin")
#' # [1] "AMP_ED20"
guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE, only_rsi_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)
@@ -75,8 +65,10 @@ guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE, only_r
meet_criteria(search_string, allow_class = "character", has_length = 1, allow_NULL = FALSE)
}
all_found <- get_column_abx(x, info = verbose, only_rsi_columns = only_rsi_columns,
verbose = verbose, fn = "guess_ab_col")
all_found <- get_column_abx(x,
info = verbose, only_rsi_columns = only_rsi_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])
@@ -85,13 +77,16 @@ guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE, only_r
message_("No column found as input for ", search_string,
" (", ab_name(search_string, language = NULL, tolower = TRUE), ").",
add_fn = font_black,
as_note = FALSE)
as_note = FALSE
)
}
return(NULL)
} else {
if (verbose == TRUE) {
message_("Using column '", font_bold(ab_result), "' as input for ", search_string,
" (", ab_name(search_string, language = NULL, tolower = TRUE), ").")
message_(
"Using column '", font_bold(ab_result), "' as input for ", search_string,
" (", ab_name(search_string, language = NULL, tolower = TRUE), ")."
)
}
return(ab_result)
}
@@ -108,9 +103,13 @@ get_column_abx <- function(x,
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),
pkg_env$get_column_abx.call)) {
if (isTRUE(reuse_previous_result) && identical(
unique_call_id(
entire_session = FALSE,
match_fn = fn
),
pkg_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
@@ -159,7 +158,8 @@ get_column_abx <- function(x,
if (info == TRUE) {
message_(" (using only ", font_bold("the first 10,000 rows"), ")...",
appendLF = FALSE,
as_note = FALSE)
as_note = FALSE
)
}
x <- x[1:10000, , drop = FALSE]
} else if (info == TRUE) {
@@ -171,7 +171,8 @@ get_column_abx <- function(x,
# and that they have no more than 50% invalid values
vectr_antibiotics <- unlist(AB_lookup$generalised_all)
vectr_antibiotics <- vectr_antibiotics[!is.na(vectr_antibiotics) & nchar(vectr_antibiotics) >= 3]
x_columns <- vapply(FUN.VALUE = character(1),
x_columns <- vapply(
FUN.VALUE = character(1),
colnames(x),
function(col, df = x) {
if (generalise_antibiotic_name(col) %in% vectr_antibiotics ||
@@ -182,13 +183,16 @@ get_column_abx <- function(x,
} else {
return(NA_character_)
}
}, USE.NAMES = FALSE)
}, 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),
df_trans <- data.frame(
colnames = colnames(x),
abcode = suppressWarnings(as.ab(colnames(x), info = FALSE)),
stringsAsFactors = 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
@@ -207,7 +211,8 @@ get_column_abx <- function(x,
}
warning_("Invalid antibiotic reference(s): ", vector_and(names(dots)[is.na(newnames)], quotes = FALSE),
call = FALSE,
immediate = TRUE)
immediate = TRUE
)
all_okay <- FALSE
}
unexisting_cols <- which(!vapply(FUN.VALUE = logical(1), dots, function(col) all(col %in% x_columns)))
@@ -216,7 +221,8 @@ get_column_abx <- function(x,
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)
call = FALSE
)
all_okay <- FALSE
}
# turn all NULLs to NAs
@@ -257,17 +263,22 @@ get_column_abx <- function(x,
}
for (i in seq_len(length(out))) {
if (verbose == TRUE & !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), ").")
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 ",
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), ")"),
names(already_set_as), " (", ab_name(names(already_set_as), tolower = TRUE, language = NULL), ")"
),
add_fn = font_red,
immediate = verbose)
immediate = verbose
)
}
}
}
@@ -292,11 +303,16 @@ get_column_abx <- function(x,
if (info == TRUE & !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)
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
)
}
}
@@ -313,7 +329,7 @@ get_ab_from_namespace <- function(x, cols_ab) {
x_new <- character()
for (val in x) {
if (paste0("AB_", val) %in% ls(envir = asNamespace("AMR"))) {
# antibiotic group names, as defined in data-raw/_internals.R, such as `AB_CARBAPENEMS`
# 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% AB_lookup$ab) {
# separate drugs, such as `AMX`
@@ -335,7 +351,10 @@ generate_warning_abs_missing <- function(missing, any = FALSE) {
} 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)
warning_(paste0(
"Introducing NAs since", any_txt[1], " these antimicrobials ", any_txt[2], " required: ",
vector_and(missing, quotes = FALSE)
),
immediate = TRUE
)
}
+25 -24
View File
@@ -25,8 +25,7 @@
#' Italicise Taxonomic Families, Genera, Species, Subspecies
#'
#' According to the binomial nomenclature, the lowest four taxonomic levels (family, genus, species, subspecies) should be printed in italic. This function finds taxonomic names within strings and makes them italic.
#' @inheritSection lifecycle Stable Lifecycle
#' 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
@@ -35,23 +34,12 @@
#' 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".
#' @inheritSection AMR Read more on Our Website!
#' @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"))
#'
#' # since ggplot2 supports no markdown (yet), use
#' # italicise_taxonomy() and the `ggtext` package for titles:
#' \donttest{
#' if (require("ggplot2") && require("ggtext")) {
#' autoplot(example_isolates$AMC,
#' title = italicise_taxonomy("Amoxi/clav in E. coli")) +
#' theme(plot.title = ggtext::element_markdown())
#' }
#' }
italicise_taxonomy <- function(string, type = c("markdown", "ansi")) {
if (missing(type)) {
type <- "markdown"
@@ -70,7 +58,8 @@ italicise_taxonomy <- function(string, type = c("markdown", "ansi")) {
after <- "\033[23m"
}
vapply(FUN.VALUE = character(1),
vapply(
FUN.VALUE = character(1),
string,
function(s) {
s_split <- unlist(strsplit(s, " "))
@@ -78,32 +67,43 @@ italicise_taxonomy <- function(string, type = c("markdown", "ansi")) {
search_strings <- gsub("[^a-zA-Z-]", "", s_split)
ind_species <- search_strings != "" &
search_strings %in% MO_lookup[which(MO_lookup$rank %in% c("family",
search_strings %in% MO_lookup[which(MO_lookup$rank %in% c(
"family",
"genus",
"species",
"subspecies",
"infraspecies",
"subsp.")),
"subsp."
)),
"species",
drop = TRUE]
drop = TRUE
]
ind_fullname <- search_strings != "" &
search_strings %in% c(MO_lookup[which(MO_lookup$rank %in% c("family",
search_strings %in% c(
MO_lookup[which(MO_lookup$rank %in% c(
"family",
"genus",
"species",
"subspecies",
"infraspecies",
"subsp.")),
"subsp."
)),
"fullname",
drop = TRUE],
MO_lookup[which(MO_lookup$rank %in% c("family",
drop = TRUE
],
MO_lookup[which(MO_lookup$rank %in% c(
"family",
"genus",
"species",
"subspecies",
"infraspecies",
"subsp.")),
"subsp."
)),
"subspecies",
drop = TRUE])
drop = TRUE
]
)
# also support E. coli, add "E." to indices
has_previous_genera_abbr <- s_split[which(ind_species) - 1] %like_case% "^[A-Z][.]?$"
@@ -119,7 +119,8 @@ italicise_taxonomy <- function(string, type = c("markdown", "ansi")) {
s_paste
},
USE.NAMES = FALSE)
USE.NAMES = FALSE
)
}
#' @rdname italicise_taxonomy
+23 -13
View File
@@ -26,7 +26,6 @@
#' Join [microorganisms] to a Data Set
#'
#' Join the data set [microorganisms] easily to an existing data set or to a [character] vector.
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname join
#' @name join
#' @aliases join inner_join
@@ -37,28 +36,34 @@
#' @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.
#' @inheritSection AMR Read more on Our Website!
#' @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()
#'
#' 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)
#' }
#' }
inner_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
@@ -121,9 +126,14 @@ join_microorganisms <- function(type, x, by, suffix, ...) {
check_dataset_integrity()
if (!is.data.frame(x)) {
if (pkg_is_available("tibble", also_load = FALSE)) {
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) {
@@ -173,5 +183,5 @@ join_microorganisms <- function(type, x, by, suffix, ...) {
warning_("in `", type, "_join()`: the newly joined data set contains ", nrow(joined) - nrow(x), " rows more than the number of rows of `x`.")
}
joined
as_original_data_class(joined, class(x.bak))
}
+63 -34
View File
@@ -26,7 +26,6 @@
#' (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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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
@@ -82,7 +81,6 @@
#' @rdname key_antimicrobials
#' @export
#' @seealso [first_isolate()]
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
@@ -110,21 +108,29 @@
#' first_weighted = first_isolate(col_keyantimicrobials = "keyab")
#' )
#'
#' # Check the difference, in this data set it results in more isolates:
#' # 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"),
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_rsi_columns = FALSE,
...) {
if (is_null_or_grouped_tbl(x)) {
@@ -172,11 +178,14 @@ key_antimicrobials <- function(x = NULL,
if (values_new_length < values_old_length &
any(filter, na.rm = TRUE) &
message_not_thrown_before("key_antimicrobials", name)) {
warning_("in `key_antimicrobials()`: ",
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.")
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])
@@ -191,30 +200,38 @@ key_antimicrobials <- function(x = NULL,
key_ab <- rep(NA_character_, nrow(x))
key_ab[which(gramstain == "Gram-negative")] <- AMR_string(x = x,
key_ab[which(gramstain == "Gram-negative")] <- AMR_string(
x = x,
values = gram_negative,
name = "Gram-negative",
filter = gramstain == "Gram-negative",
cols = cols)
cols = cols
)
key_ab[which(gramstain == "Gram-positive")] <- AMR_string(x = x,
key_ab[which(gramstain == "Gram-positive")] <- AMR_string(
x = x,
values = gram_positive,
name = "Gram-positive",
filter = gramstain == "Gram-positive",
cols = cols)
cols = cols
)
key_ab[which(kingdom == "Fungi")] <- AMR_string(x = x,
key_ab[which(kingdom == "Fungi")] <- AMR_string(
x = x,
values = antifungal,
name = "antifungal",
filter = kingdom == "Fungi",
cols = cols)
cols = cols
)
# back-up - only use `universal`
key_ab[which(is.na(key_ab))] <- AMR_string(x = x,
key_ab[which(is.na(key_ab))] <- AMR_string(
x = x,
values = character(0),
name = "",
filter = is.na(key_ab),
cols = cols)
cols = cols
)
if (length(unique(key_ab)) == 1) {
warning_("in `key_antimicrobials()`: no distinct key antibiotics determined.")
@@ -238,10 +255,12 @@ all_antimicrobials <- function(x = NULL,
# force regular data.frame, not a tibble or data.table
x <- as.data.frame(x, stringsAsFactors = FALSE)
cols <- get_column_abx(x, only_rsi_columns = only_rsi_columns, info = FALSE,
sort = FALSE, fn = "all_antimicrobials")
cols <- get_column_abx(x,
only_rsi_columns = only_rsi_columns, info = FALSE,
sort = FALSE, fn = "all_antimicrobials"
)
generate_antimcrobials_string(x[ , cols, drop = FALSE])
generate_antimcrobials_string(x[, cols, drop = FALSE])
}
generate_antimcrobials_string <- function(df) {
@@ -251,16 +270,22 @@ generate_antimcrobials_string <- function(df) {
if (NROW(df) == 0) {
return(character(0))
}
tryCatch({
do.call(paste0,
lapply(as.list(df),
tryCatch(
{
do.call(
paste0,
lapply(
as.list(df),
function(x) {
x <- toupper(as.character(x))
x[!x %in% c("R", "S", "I")] <- "."
paste(x)
}))
}
)
)
},
error = function(e) rep(strrep(".", NCOL(df)), NROW(df)))
error = function(e) rep(strrep(".", NCOL(df)), NROW(df))
)
}
#' @rdname key_antimicrobials
@@ -322,14 +347,18 @@ antimicrobials_equal <- function(y,
all(a == b, na.rm = TRUE)
}
}
out <- unlist(mapply(FUN = determine_equality,
out <- unlist(mapply(
FUN = determine_equality,
y,
z,
MoreArgs = list(type = type,
MoreArgs = list(
type = type,
points_threshold = points_threshold,
ignore_I = ignore_I),
ignore_I = ignore_I
),
SIMPLIFY = FALSE,
USE.NAMES = FALSE))
USE.NAMES = FALSE
))
out[is.na(y) | is.na(z)] <- NA
out
}
+3 -2
View File
@@ -26,14 +26,15 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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
#' @inheritSection AMR Read more on Our Website!
#' @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)
-54
View File
@@ -1,54 +0,0 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
###############
# NOTE TO SELF: could also have done this with the 'lifecycle' package, but why add a package dependency for such an easy job??
###############
#' Lifecycles of Functions in the `AMR` Package
#' @name lifecycle
#' @rdname lifecycle
#' @description Functions in this `AMR` package are categorised using [the lifecycle circle of the Tidyverse as found on www.tidyverse.org/lifecycle](https://lifecycle.r-lib.org/articles/stages.html).
#'
#' \if{html}{\figure{lifecycle_tidyverse.svg}{options: height="200" style=margin-bottom:"5"} \cr}
#' This page contains a section for every lifecycle (with text borrowed from the aforementioned Tidyverse website), so they can be used in the manual pages of the functions.
#' @section Experimental Lifecycle:
#' \if{html}{\figure{lifecycle_experimental.svg}{options: style=margin-bottom:"5"} \cr}
#' The [lifecycle][AMR::lifecycle] of this function is **experimental**. An experimental function is in early stages of development. The unlying code might be changing frequently. Experimental functions might be removed without deprecation, so you are generally best off waiting until a function is more mature before you use it in production code. Experimental functions are only available in development versions of this `AMR` package and will thus not be included in releases that are submitted to CRAN, since such functions have not yet matured enough.
#' @section Maturing Lifecycle:
#' \if{html}{\figure{lifecycle_maturing.svg}{options: style=margin-bottom:"5"} \cr}
#' The [lifecycle][AMR::lifecycle] of this function is **maturing**. The unlying code of a maturing function has been roughed out, but finer details might still change. Since this function needs wider usage and more extensive testing, you are very welcome [to suggest changes at our repository](https://github.com/msberends/AMR/issues) or [write us an email (see section 'Contact Us')][AMR::AMR].
#' @section Stable Lifecycle:
#' \if{html}{\figure{lifecycle_stable.svg}{options: style=margin-bottom:"5"} \cr}
#' The [lifecycle][AMR::lifecycle] of this function is **stable**. In a stable function, major changes are unlikely. This means that the unlying code will generally evolve by adding new arguments; removing arguments or changing the meaning of existing arguments will be avoided.
#'
#' If the unlying code needs breaking changes, they will occur gradually. For example, an argument will be deprecated and first continue to work, but will emit a message informing you of the change. Next, typically after at least one newly released version on CRAN, the message will be transformed to an error.
#' @section Retired Lifecycle:
#' \if{html}{\figure{lifecycle_retired.svg}{options: style=margin-bottom:"5"} \cr}
#' The [lifecycle][AMR::lifecycle] of this function is **retired**. A retired function is no longer under active development, and (if appropiate) a better alternative is available. No new arguments will be added, and only the most critical bugs will be fixed. In a future version, this function will be removed.
#' @section Questioning Lifecycle:
#' \if{html}{\figure{lifecycle_questioning.svg}{options: style=margin-bottom:"5"} \cr}
#' The [lifecycle][AMR::lifecycle] of this function is **questioning**. This function might be no longer be optimal approach, or is it questionable whether this function should be in this `AMR` package at all.
NULL
+12 -17
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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.
@@ -44,33 +43,25 @@
#' 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()]
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' a <- "This is a test"
#' b <- "TEST"
#' a %like% b
#' #> TRUE
#' b %like% a
#' #> FALSE
#'
#' # also supports multiple patterns
#' a <- c("Test case", "Something different", "Yet another thing")
#' b <- c( "case", "diff", "yet")
#' b <- c("case", "diff", "yet")
#' a %like% b
#' #> TRUE TRUE TRUE
#' a %unlike% b
#' #> FALSE FALSE FALSE
#'
#' a[1] %like% b
#' #> TRUE FALSE FALSE
#' a %like% b[1]
#' #> TRUE FALSE FALSE
#'
#' # get isolates whose name start with 'Ent' or 'ent'
#' example_isolates[which(mo_name(example_isolates$mo) %like% "^ent"), ]
#' \donttest{
#' # faster way, since mo_name() is context-aware:
#' example_isolates[which(mo_name() %like% "^ent"), ]
#' # get isolates whose name start with 'Entero' (case-insensitive)
#' example_isolates[which(mo_name() %like% "^entero"), ]
#'
#' if (require("dplyr")) {
#' example_isolates %>%
@@ -105,18 +96,22 @@ like <- function(x, pattern, ignore.case = TRUE) {
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), ")")
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(
mapply(FUN = grepl,
mapply(
FUN = grepl,
x = x,
pattern = pattern,
fixed = fixed,
perl = !fixed,
MoreArgs = list(ignore.case = FALSE),
SIMPLIFY = FALSE,
USE.NAMES = FALSE)
USE.NAMES = FALSE
)
)
}
}
+631 -363
View File
File diff suppressed because it is too large Load Diff
+93 -48
View File
@@ -25,29 +25,51 @@
# these are allowed MIC values and will become [factor] levels
ops <- c("<", "<=", "", ">=", ">")
valid_mic_levels <- c(c(t(vapply(FUN.VALUE = character(9), ops,
function(x) paste0(x, "0.00", 1:9)))),
unique(c(t(vapply(FUN.VALUE = character(104), ops,
function(x) paste0(x, sort(as.double(paste0("0.0",
sort(c(1:99, 125, 128, 256, 512, 625)))))))))),
unique(c(t(vapply(FUN.VALUE = character(103), ops,
function(x) paste0(x, sort(as.double(paste0("0.",
c(1:99, 125, 128, 256, 512))))))))),
c(t(vapply(FUN.VALUE = character(10), ops,
function(x) paste0(x, sort(c(1:9, 1.5)))))),
c(t(vapply(FUN.VALUE = character(45), ops,
function(x) paste0(x, c(10:98)[9:98 %% 2 == TRUE])))),
c(t(vapply(FUN.VALUE = character(17), ops,
function(x) paste0(x, sort(c(2 ^ c(7:11), 192, 80 * c(2:12))))))))
valid_mic_levels <- c(
c(t(vapply(
FUN.VALUE = character(9), ops,
function(x) paste0(x, "0.00", 1:9)
))),
unique(c(t(vapply(
FUN.VALUE = character(104), ops,
function(x) {
paste0(x, sort(as.double(paste0(
"0.0",
sort(c(1:99, 125, 128, 256, 512, 625))
))))
}
)))),
unique(c(t(vapply(
FUN.VALUE = character(103), ops,
function(x) {
paste0(x, sort(as.double(paste0(
"0.",
c(1:99, 125, 128, 256, 512)
))))
}
)))),
c(t(vapply(
FUN.VALUE = character(10), ops,
function(x) paste0(x, sort(c(1:9, 1.5)))
))),
c(t(vapply(
FUN.VALUE = character(45), ops,
function(x) paste0(x, c(10:98)[9:98 %% 2 == TRUE])
))),
c(t(vapply(
FUN.VALUE = character(17), ops,
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.
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname as.mic
#' @param x a [character] or [numeric] vector
#' @param na.rm a [logical] indicating whether missing values should be removed
#' @details To interpret MIC values as RSI values, use [as.rsi()] on MIC values. It supports guidelines from EUCAST and CLSI.
#' @param ... arguments passed on to methods
#' @details To interpret MIC values as RSI values, use [as.rsi()] on MIC values. It supports guidelines from EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, 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:
#'
@@ -86,36 +108,54 @@ valid_mic_levels <- c(c(t(vapply(FUN.VALUE = character(9), ops,
#' ```
#'
#' 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.rsi()]
#' @inheritSection AMR Read more on Our Website!
#' @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/RSI values:
#' as.mic("<=0.002; S") # will return <=0.002
#' as.mic("<=0.002; S")
#'
#' # mathematical processing treats MICs as [numeric] values
#' # mathematical processing treats MICs as numeric values
#' fivenum(mic_data)
#' quantile(mic_data)
#' all(mic_data < 512)
#'
#' # interpret MIC values
#' as.rsi(x = as.mic(2),
#' mo = as.mo("S. pneumoniae"),
#' as.rsi(
#' x = as.mic(2),
#' mo = as.mo("Streptococcus pneumoniae"),
#' ab = "AMX",
#' guideline = "EUCAST")
#' as.rsi(x = as.mic(4),
#' mo = as.mo("S. pneumoniae"),
#' guideline = "EUCAST"
#' )
#' as.rsi(
#' x = as.mic(c(0.01, 2, 4, 8)),
#' mo = as.mo("Streptococcus pneumoniae"),
#' ab = "AMX",
#' guideline = "EUCAST")
#' 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
#' }
#' if (require("ggplot2")) {
#' autoplot(mic_data, mo = "E. coli", ab = "cipro", language = "uk") # Ukrainian
#' }
as.mic <- function(x, na.rm = FALSE) {
meet_criteria(x, allow_class = c("mic", "character", "numeric", "integer", "factor"), allow_NA = TRUE)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
@@ -127,6 +167,7 @@ as.mic <- function(x, na.rm = FALSE) {
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
x[trimws(x) == ""] <- NA
x.bak <- x
# comma to period
@@ -178,11 +219,14 @@ as.mic <- function(x, na.rm = FALSE) {
warning_("in `as.mic()`: ", na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid MICs: ",
list_missing, call = FALSE)
list_missing,
call = FALSE
)
}
set_clean_class(factor(x, levels = valid_mic_levels, ordered = TRUE),
new_class = c("mic", "ordered", "factor"))
new_class = c("mic", "ordered", "factor")
)
}
}
@@ -191,15 +235,18 @@ all_valid_mics <- function(x) {
return(FALSE)
}
x_mic <- tryCatch(suppressWarnings(as.mic(x[!is.na(x)])),
error = function(e) NA)
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.
#' @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"))
new_class = c("mic", "ordered", "factor")
)
#' @rdname as.mic
#' @export
@@ -214,13 +261,6 @@ as.double.mic <- function(x, ...) {
as.double(gsub("[<=>]+", "", as.character(x), perl = TRUE))
}
#' @method as.integer mic
#' @export
#' @noRd
as.integer.mic <- function(x, ...) {
as.integer(gsub("[<=>]+", "", as.character(x), perl = TRUE))
}
#' @method as.numeric mic
#' @export
#' @noRd
@@ -228,11 +268,12 @@ 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, defaults to `FALSE`
#' @export
#' @noRd
droplevels.mic <- function(x, exclude = if (any(is.na(levels(x)))) NULL else NA, as.mic = TRUE, ...) {
x <- droplevels.factor(x, exclude = exclude, ...)
droplevels.mic <- function(x, as.mic = FALSE, ...) {
x <- droplevels.factor(x, ...)
if (as.mic == TRUE) {
class(x) <- c("mic", "ordered", "factor")
}
@@ -260,7 +301,11 @@ type_sum.mic <- function(x, ...) {
#' @export
#' @noRd
print.mic <- function(x, ...) {
cat("Class <mic>\n")
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)) {
@@ -366,12 +411,12 @@ hist.mic <- function(x, ...) {
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)
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)
)
}
@@ -667,7 +712,7 @@ is_lower <- function(el) {
#' @export
#' @noRd
`^.mic` <- function(e1, e2) {
as.double(e1) ^ as.double(e2)
as.double(e1)^as.double(e2)
}
#' @method %% mic
+449 -265
View File
File diff suppressed because it is too large Load Diff
+12 -8
View File
@@ -26,8 +26,7 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @author Dr Matthijs Berends
#' @author Dr. Matthijs Berends
#' @param x Any user input value(s)
#' @param n A full taxonomic name, that exists in [`microorganisms$fullname`][microorganisms]
#' @section Matching Score for Microorganisms:
@@ -53,13 +52,14 @@
#' Since `AMR` version 1.8.1, common microorganism abbreviations are ignored in determining the matching score. These abbreviations are currently: `r vector_and(pkg_env$mo_field_abbreviations, quotes = FALSE)`.
#' @export
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' as.mo("E. coli")
#' mo_uncertainties()
#'
#' mo_matching_score(x = "E. coli",
#' n = c("Escherichia coli", "Entamoeba coli"))
#' 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")
@@ -69,10 +69,14 @@ mo_matching_score <- function(x, n) {
x <- gsub("[^a-zA-Z0-9 \\(\\)]+", "", x)
# remove abbreviations known to the field
x <- gsub(paste0("(^|[^a-z0-9]+)(",
x <- gsub(paste0(
"(^|[^a-z0-9]+)(",
paste0(pkg_env$mo_field_abbreviations, collapse = "|"),
")([^a-z0-9]+|$)"),
"", x, perl = TRUE, ignore.case = TRUE)
")([^a-z0-9]+|$)"
),
"", x,
perl = TRUE, ignore.case = TRUE
)
# only keep one space
x <- gsub(" +", " ", x)
+103 -90
View File
@@ -26,7 +26,6 @@
#' 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*.
#' @inheritSection lifecycle Stable Lifecycle
#' @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"`
#' @param language language of the returned text, defaults to system language (see [get_AMR_locale()]) and can be overwritten by setting the option `AMR_locale`, e.g. `options(AMR_locale = "de")`, see [translate]. Also used to translate text like "no growth". Use `language = NULL` or `language = ""` to prevent translation.
@@ -67,93 +66,93 @@
#' @export
#' @seealso Data set [microorganisms]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # taxonomic tree -----------------------------------------------------------
#' mo_kingdom("E. coli") # "Bacteria"
#' mo_phylum("E. coli") # "Proteobacteria"
#' mo_class("E. coli") # "Gammaproteobacteria"
#' mo_order("E. coli") # "Enterobacterales"
#' mo_family("E. coli") # "Enterobacteriaceae"
#' mo_genus("E. coli") # "Escherichia"
#' mo_species("E. coli") # "coli"
#' mo_subspecies("E. coli") # ""
#' 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")
#'
#' # colloquial properties ----------------------------------------------------
#' mo_name("E. coli") # "Escherichia coli"
#' mo_fullname("E. coli") # "Escherichia coli" - same as mo_name()
#' mo_shortname("E. coli") # "E. coli"
#' mo_name("Klebsiella pneumoniae")
#' mo_fullname("Klebsiella pneumoniae")
#' mo_shortname("Klebsiella pneumoniae")
#'
#' # other properties ---------------------------------------------------------
#' mo_gramstain("E. coli") # "Gram-negative"
#' mo_snomed("E. coli") # 112283007, 116395006, ... (SNOMED codes)
#' mo_type("E. coli") # "Bacteria" (equal to kingdom, but may be translated)
#' mo_rank("E. coli") # "species"
#' mo_url("E. coli") # get the direct url to the online database entry
#' mo_synonyms("E. coli") # get previously accepted taxonomic names
#' mo_gramstain("Klebsiella pneumoniae")
#' mo_snomed("Klebsiella pneumoniae")
#' mo_type("Klebsiella pneumoniae")
#' mo_rank("Klebsiella pneumoniae")
#' mo_url("Klebsiella pneumoniae")
#' mo_synonyms("Klebsiella pneumoniae")
#'
#' # scientific reference -----------------------------------------------------
#' mo_ref("E. coli") # "Castellani et al., 1919"
#' mo_authors("E. coli") # "Castellani et al."
#' mo_year("E. coli") # 1919
#' mo_lpsn("E. coli") # 776057 (LPSN record ID)
#' mo_ref("Klebsiella pneumoniae")
#' mo_authors("Klebsiella pneumoniae")
#' mo_year("Klebsiella pneumoniae")
#' mo_lpsn("Klebsiella pneumoniae")
#'
#' # abbreviations known in the field -----------------------------------------
#' mo_genus("MRSA") # "Staphylococcus"
#' mo_species("MRSA") # "aureus"
#' mo_shortname("VISA") # "S. aureus"
#' mo_gramstain("VISA") # "Gram-positive"
#' mo_genus("MRSA")
#' mo_species("MRSA")
#' mo_shortname("VISA")
#' mo_gramstain("VISA")
#'
#' mo_genus("EHEC") # "Escherichia"
#' mo_species("EHEC") # "coli"
#' mo_genus("EHEC")
#' mo_species("EHEC")
#'
#' # known subspecies ---------------------------------------------------------
#' mo_name("doylei") # "Campylobacter jejuni doylei"
#' mo_genus("doylei") # "Campylobacter"
#' mo_species("doylei") # "jejuni"
#' mo_subspecies("doylei") # "doylei"
#' mo_name("doylei")
#' mo_genus("doylei")
#' mo_species("doylei")
#' mo_subspecies("doylei")
#'
#' mo_fullname("K. pneu rh") # "Klebsiella pneumoniae rhinoscleromatis"
#' mo_shortname("K. pneu rh") # "K. pneumoniae"
#' mo_fullname("K. pneu rh")
#' mo_shortname("K. pneu rh")
#'
#' \donttest{
#' # Becker classification, see ?as.mo ----------------------------------------
#' mo_fullname("S. epi") # "Staphylococcus epidermidis"
#' mo_fullname("S. epi", Becker = TRUE) # "Coagulase-negative Staphylococcus (CoNS)"
#' mo_shortname("S. epi") # "S. epidermidis"
#' mo_shortname("S. epi", Becker = TRUE) # "CoNS"
#' mo_fullname("S. epi")
#' mo_fullname("S. epi", Becker = TRUE)
#' mo_shortname("S. epi")
#' mo_shortname("S. epi", Becker = TRUE)
#'
#' # Lancefield classification, see ?as.mo ------------------------------------
#' mo_fullname("S. pyo") # "Streptococcus pyogenes"
#' mo_fullname("S. pyo", Lancefield = TRUE) # "Streptococcus group A"
#' mo_shortname("S. pyo") # "S. pyogenes"
#' mo_shortname("S. pyo", Lancefield = TRUE) # "GAS" (='Group A Streptococci')
#' mo_fullname("S. pyo")
#' mo_fullname("S. pyo", Lancefield = TRUE)
#' mo_shortname("S. pyo")
#' mo_shortname("S. pyo", Lancefield = TRUE)
#'
#'
#' # language support --------------------------------------------------------
#' mo_gramstain("E. coli", language = "de") # "Gramnegativ"
#' mo_gramstain("E. coli", language = "nl") # "Gram-negatief"
#' mo_gramstain("E. coli", language = "es") # "Gram negativo"
#' mo_gramstain("Klebsiella pneumoniae", language = "de")
#' mo_gramstain("Klebsiella pneumoniae", language = "nl")
#' mo_gramstain("Klebsiella pneumoniae", language = "es")
#'
#' # mo_type is equal to mo_kingdom, but mo_kingdom will remain official
#' mo_kingdom("E. coli") # "Bacteria" on a German system
#' mo_type("E. coli") # "Bakterien" on a German system
#' mo_type("E. coli") # "Bacteria" on an English system
#' mo_kingdom("Klebsiella pneumoniae")
#' mo_type("Klebsiella pneumoniae")
#' mo_type("Klebsiella pneumoniae")
#'
#' mo_fullname("S. pyogenes",
#' Lancefield = TRUE,
#' language = "de") # "Streptococcus Gruppe A"
#' language = "de"
#' )
#' mo_fullname("S. pyogenes",
#' Lancefield = TRUE,
#' language = "nl") # "Streptococcus groep A"
#' language = "nl"
#' )
#'
#'
#' # other --------------------------------------------------------------------
#'
#' mo_is_yeast(c("Candida", "E. coli")) # TRUE, FALSE
#' mo_is_yeast(c("Candida", "Trichophyton", "Klebsiella"))
#'
#' # gram stains and intrinsic resistance can also be used as a filter in dplyr verbs
#' \donttest{
#' # gram stains and intrinsic resistance can be used as a filter in dplyr verbs
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter(mo_is_gram_positive())
@@ -164,11 +163,11 @@
#'
#'
#' # get a list with the complete taxonomy (from kingdom to subspecies)
#' mo_taxonomy("E. coli")
#' mo_taxonomy("Klebsiella pneumoniae")
#'
#' # get a list with the taxonomy, the authors, Gram-stain,
#' # SNOMED codes, and URL to the online database
#' mo_info("E. coli")
#' }
#' mo_info("Klebsiella pneumoniae")
#' }
mo_name <- function(x, language = get_AMR_locale(), ...) {
if (missing(x)) {
@@ -178,10 +177,11 @@ mo_name <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "fullname", language = language, ...),
translate_into_language(mo_validate(x = x, property = "fullname", language = language, ...),
language = language,
only_unknown = FALSE,
only_affect_mo_names = TRUE)
only_affect_mo_names = TRUE
)
}
#' @rdname mo_property
@@ -223,7 +223,7 @@ mo_shortname <- function(x, language = get_AMR_locale(), ...) {
shortnames[is.na(x.mo)] <- NA_character_
load_mo_failures_uncertainties_renamed(metadata)
translate_AMR(shortnames, language = language, only_unknown = FALSE, only_affect_mo_names = TRUE)
translate_into_language(shortnames, language = language, only_unknown = FALSE, only_affect_mo_names = TRUE)
}
@@ -238,7 +238,7 @@ mo_subspecies <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "subspecies", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "subspecies", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -251,7 +251,7 @@ mo_species <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "species", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "species", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -264,7 +264,7 @@ mo_genus <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "genus", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "genus", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -277,7 +277,7 @@ mo_family <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "family", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "family", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -290,7 +290,7 @@ mo_order <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "order", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "order", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -303,7 +303,7 @@ mo_class <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "class", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "class", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -316,7 +316,7 @@ mo_phylum <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "phylum", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "phylum", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -329,7 +329,7 @@ mo_kingdom <- function(x, language = get_AMR_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = "kingdom", language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = "kingdom", language = language, ...), language = language, only_unknown = TRUE)
}
#' @rdname mo_property
@@ -349,7 +349,7 @@ mo_type <- function(x, language = get_AMR_locale(), ...) {
x.mo <- as.mo(x, language = language, ...)
out <- mo_kingdom(x.mo, language = NULL)
out[which(mo_is_yeast(x.mo))] <- "Yeasts"
translate_AMR(out, language = language, only_unknown = FALSE)
translate_into_language(out, language = language, only_unknown = FALSE)
}
#' @rdname mo_property
@@ -370,17 +370,19 @@ mo_gramstain <- function(x, language = get_AMR_locale(), ...) {
x[mo_kingdom(x.mo) == "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) %in% c("Actinobacteria",
x[(mo_phylum(x.mo) %in% c(
"Actinobacteria",
"Chloroflexi",
"Firmicutes",
"Tenericutes") &
"Tenericutes"
) &
# but class Negativicutes (of phylum Firmicutes) are Gram-negative!
mo_class(x.mo) != "Negativicutes")
# and of course our own ID for Gram-positives
| x.mo == "B_GRAMP"] <- "Gram-positive"
load_mo_failures_uncertainties_renamed(metadata)
translate_AMR(x, language = language, only_unknown = FALSE)
translate_into_language(x, language = language, only_unknown = FALSE)
}
#' @rdname mo_property
@@ -435,9 +437,7 @@ mo_is_yeast <- function(x, language = get_AMR_locale(), ...) {
metadata <- get_mo_failures_uncertainties_renamed()
x.kingdom <- mo_kingdom(x.mo, language = NULL)
x.phylum <- mo_phylum(x.mo, language = NULL)
x.class <- mo_class(x.mo, language = NULL)
x.order <- mo_order(x.mo, language = NULL)
load_mo_failures_uncertainties_renamed(metadata)
@@ -472,9 +472,11 @@ mo_is_intrinsic_resistant <- function(x, ab, language = get_AMR_locale(), ...) {
# show used version number once per session (pkg_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 ",
message_(
"Determining intrinsic resistance based on ",
format_eucast_version_nr(3.3, markdown = FALSE), ". ",
font_red("This note will be shown once per session."))
font_red("This note will be shown once per session.")
)
}
# runs against internal vector: INTRINSIC_R (see zzz.R)
@@ -578,14 +580,16 @@ mo_taxonomy <- function(x, language = get_AMR_locale(), ...) {
x <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
out <- list(kingdom = mo_kingdom(x, language = language),
out <- list(
kingdom = mo_kingdom(x, language = language),
phylum = mo_phylum(x, language = language),
class = mo_class(x, language = language),
order = mo_order(x, language = language),
family = mo_family(x, language = language),
genus = mo_genus(x, language = language),
species = mo_species(x, language = language),
subspecies = mo_subspecies(x, language = language))
subspecies = mo_subspecies(x, language = language)
)
load_mo_failures_uncertainties_renamed(metadata)
out
@@ -606,7 +610,7 @@ mo_synonyms <- function(x, language = get_AMR_locale(), ...) {
IDs <- mo_name(x = x, language = NULL)
syns <- lapply(IDs, function(newname) {
res <- sort(microorganisms.old[which(microorganisms.old$fullname_new == newname), "fullname"])
res <- sort(microorganisms.old[which(microorganisms.old$fullname_new == newname), "fullname", drop = TRUE])
if (length(res) == 0) {
NULL
} else {
@@ -637,13 +641,18 @@ mo_info <- function(x, language = get_AMR_locale(), ...) {
x <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
info <- lapply(x, function(y)
c(mo_taxonomy(y, language = language),
list(synonyms = mo_synonyms(y),
info <- lapply(x, function(y) {
c(
mo_taxonomy(y, language = language),
list(
synonyms = mo_synonyms(y),
gramstain = mo_gramstain(y, language = language),
url = unname(mo_url(y, open = FALSE)),
ref = mo_ref(y),
snomed = unlist(mo_snomed(y)))))
snomed = unlist(mo_snomed(y))
)
)
})
if (length(info) > 1) {
names(info) <- mo_name(x)
result <- info
@@ -669,10 +678,11 @@ mo_url <- function(x, open = FALSE, language = get_AMR_locale(), ...) {
x.mo <- as.mo(x = x, language = language, ... = ...)
metadata <- get_mo_failures_uncertainties_renamed()
df <- microorganisms[match(x.mo, microorganisms$mo), c("mo", "fullname", "source", "kingdom", "rank")]
df <- microorganisms[match(x.mo, microorganisms$mo), c("mo", "fullname", "source", "kingdom", "rank"), drop = FALSE]
df$url <- ifelse(df$source == "LPSN",
paste0(CATALOGUE_OF_LIFE$url_LPSN, "/species/", gsub(" ", "-", tolower(df$fullname), fixed = TRUE)),
paste0(CATALOGUE_OF_LIFE$url_CoL, "/data/search?type=EXACT&q=", gsub(" ", "%20", df$fullname, fixed = TRUE)))
paste0(CATALOGUE_OF_LIFE$url_CoL, "/data/search?type=EXACT&q=", gsub(" ", "%20", df$fullname, fixed = TRUE))
)
genera <- which(df$kingdom == "Bacteria" & df$rank == "genus")
df$url[genera] <- gsub("/species/", "/genus/", df$url[genera], fixed = TRUE)
@@ -705,7 +715,7 @@ mo_property <- function(x, property = "fullname", language = get_AMR_locale(), .
meet_criteria(property, allow_class = "character", has_length = 1, is_in = colnames(microorganisms))
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
translate_AMR(mo_validate(x = x, property = property, language = language, ...), language = language, only_unknown = TRUE)
translate_into_language(mo_validate(x = x, property = property, language = language, ...), language = language, only_unknown = TRUE)
}
mo_validate <- function(x, property, language, ...) {
@@ -724,12 +734,12 @@ mo_validate <- function(x, property, language, ...) {
if (tryCatch(all(x[!is.na(x)] %in% MO_lookup$mo) & !has_Becker_or_Lancefield, error = function(e) FALSE)) {
# special case for mo_* functions where class is already <mo>
x <- MO_lookup[match(x, MO_lookup$mo), 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% MO_lookup[1, property, drop = TRUE],
error = function(e) stop(e$message, call. = FALSE))
error = function(e) stop(e$message, call. = FALSE)
)
if (!all(x[!is.na(x)] %in% MO_lookup[, property, drop = TRUE]) | has_Becker_or_Lancefield) {
x <- exec_as.mo(x, property = property, language = language, ...)
@@ -752,9 +762,12 @@ find_mo_col <- function(fn) {
# 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({
try(
{
mo <- suppressMessages(search_type_in_df(df, "mo"))
}, silent = TRUE)
},
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, "()`")
+45 -33
View File
@@ -28,17 +28,16 @@
#' @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.
#' @inheritSection lifecycle Stable Lifecycle
#' @param path location of your reference file, see *Details*. Can be `""`, `NULL` or `FALSE` to delete the reference file.
#' @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, default to 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] 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 as an \R option, using `options(AMR_mo_source = "my/location/file.rds")`.
#' [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 as an \R option, using `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 to the compressed data file.
#' 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.
#'
@@ -46,14 +45,14 @@
#'
#' @section How to Setup:
#'
#' Imagine this data on a sheet of an Excel file (mo codes were looked up in the [microorganisms] data set). The first column contains the organisation specific codes, the second column contains an MO code from this package:
#' 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 | B_ESCHR_COLI |
#' 3 | lab_mo_kpneumoniae | B_KLBSL_PNMN |
#' 2 | lab_mo_ecoli | Escherichia coli |
#' 3 | lab_mo_kpneumoniae | Klebsiella pneumoniae |
#' 4 | | |
#' ```
#'
@@ -90,11 +89,11 @@
#'
#' ```
#' | A | B |
#' --|--------------------|--------------|
#' --|--------------------|-----------------------|
#' 1 | Organisation XYZ | mo |
#' 2 | lab_mo_ecoli | B_ESCHR_COLI |
#' 3 | lab_mo_kpneumoniae | B_KLBSL_PNMN |
#' 4 | lab_Staph_aureus | B_STPHY_AURS |
#' 2 | lab_mo_ecoli | Escherichia coli |
#' 3 | lab_mo_kpneumoniae | Klebsiella pneumoniae |
#' 4 | lab_Staph_aureus | Staphylococcus aureus |
#' 5 | | |
#' ```
#'
@@ -121,7 +120,6 @@
#'
#' 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
#' @inheritSection AMR Read more on Our Website!
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)
@@ -137,44 +135,51 @@ set_mo_source <- function(path, destination = getOption("AMR_mo_source", "~/mo_s
unlink(mo_source_destination)
message_("Removed mo_source file '", font_bold(mo_source_destination), "'",
add_fn = font_red,
as_note = FALSE)
as_note = FALSE
)
}
return(invisible())
}
stop_ifnot(file.exists(path), "file not found: ", path)
df <- NULL
if (path %like% "[.]rds$") {
df <- readRDS(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(header = TRUE, sep = "\t", stringsAsFactors = FALSE)
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(header = TRUE, sep = ",", stringsAsFactors = FALSE),
silent = TRUE)
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(header = TRUE, sep = "\t", stringsAsFactors = FALSE),
silent = TRUE)
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(header = TRUE, sep = "|", stringsAsFactors = FALSE),
silent = TRUE)
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))
@@ -187,7 +192,7 @@ set_mo_source <- function(path, destination = getOption("AMR_mo_source", "~/mo_s
}
df <- as.data.frame(df, stringAsFactors = FALSE)
df[, "mo"] <- set_clean_class(df[, "mo", drop = TRUE], c("mo", "character"))
df[, "mo"] <- as.mo(df[, "mo", drop = TRUE])
# success
if (file.exists(mo_source_destination)) {
@@ -195,11 +200,15 @@ set_mo_source <- function(path, destination = getOption("AMR_mo_source", "~/mo_s
} 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 '",
txt <- paste0(
word_wrap(paste0(
"This will write create the new file '",
mo_source_destination,
"', for which your permission is needed.")),
"', for which your permission is needed."
)),
"\n\n",
word_wrap("Do you agree that this file will be created?"))
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 in home directory", txt)
@@ -215,11 +224,13 @@ set_mo_source <- function(path, destination = getOption("AMR_mo_source", "~/mo_s
attr(df, "mo_source_timestamp") <- file.mtime(path)
saveRDS(df, mo_source_destination)
pkg_env$mo_source <- df
message_(action, " mo_source file '", font_bold(mo_source_destination),
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], '"')
'), columns "', colnames(df)[1], '" and "', colnames(df)[2], '"'
)
}
#' @rdname mo_source
@@ -275,9 +286,9 @@ check_validity_mo_source <- function(x, refer_to_name = "`reference_df`", stop_o
return(FALSE)
}
}
if (!all(x$mo %in% c("", microorganisms$mo), na.rm = TRUE)) {
if (!all(x$mo %in% c("", microorganisms$mo, microorganisms$fullname), na.rm = TRUE)) {
if (stop_on_error == TRUE) {
invalid <- x[which(!x$mo %in% c("", microorganisms$mo)), , drop = FALSE]
invalid <- x[which(!x$mo %in% c("", microorganisms$mo, microorganisms$fullname)), , drop = FALSE]
if (nrow(invalid) > 1) {
plural <- "s"
} else {
@@ -286,7 +297,8 @@ check_validity_mo_source <- function(x, refer_to_name = "`reference_df`", stop_o
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)
call = FALSE
)
} else {
return(FALSE)
}
+25 -11
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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
@@ -36,7 +35,6 @@
#' @return An object of classes [pca] and [prcomp]
#' @importFrom stats prcomp
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a data set available in the AMR package.
#' # See ?example_isolates.
@@ -45,8 +43,11 @@
#' 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;
#' 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.rsi, resistance) # then get resistance of all drugs
#'
#' # now conduct PCA for certain antimicrobial agents
@@ -55,8 +56,17 @@
#'
#' pca_result
#' summary(pca_result)
#'
#' # old base R plotting method:
#' biplot(pca_result)
#' ggplot_pca(pca_result) # a new and convenient plot function
#' # new ggplot2 plotting method using this package:
#' ggplot_pca(pca_result)
#'
#' if (require("ggplot2")) {
#' ggplot_pca(pca_result) +
#' scale_colour_viridis_d() +
#' labs(title = "Title here")
#' }
#' }
#' }
pca <- function(x,
@@ -84,7 +94,8 @@ pca <- function(x,
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))
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")
@@ -103,10 +114,11 @@ pca <- function(x,
# set column names
tryCatch(colnames(x) <- as.character(dots)[2:length(dots)],
error = function(e) warning("column names could not be set"))
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))]
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)
}
@@ -114,10 +126,12 @@ pca <- function(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)))]
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), ".")
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
+149 -84
View File
@@ -26,8 +26,7 @@
#' Plotting for Classes `rsi`, `mic` and `disk`
#'
#' Functions to plot classes `rsi`, `mic` and `disk`, with support for base \R and `ggplot2`.
#' @inheritSection lifecycle Stable Lifecycle
#' @inheritSection AMR Read more on Our Website!
#' @param x,object values created with [as.mic()], [as.disk()] or [as.rsi()] (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 code with [as.ab()]
@@ -61,11 +60,16 @@
#' # 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 = "uk")
#'
#' \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_rsi_values)
#' }
#' }
@@ -79,7 +83,7 @@ plot.mic <- function(x,
mo = NULL,
ab = NULL,
guideline = "EUCAST",
main = paste("MIC values of", deparse(substitute(x))),
main = deparse(substitute(x)),
ylab = "Frequency",
xlab = "Minimum Inhibitory Concentration (mg/L)",
colours_RSI = c("#ED553B", "#3CAEA3", "#F6D55C"),
@@ -98,10 +102,10 @@ plot.mic <- function(x,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if (length(colours_RSI) == 1) {
@@ -111,21 +115,24 @@ plot.mic <- function(x,
x <- plot_prepare_table(x, expand = expand)
cols_sub <- plot_colours_subtitle_guideline(x = x,
cols_sub <- plot_colours_subtitle_guideline(
x = x,
mo = mo,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
fn = as.mic,
language = language,
...)
...
)
barplot(x,
col = cols_sub$cols,
main = main,
ylim = c(0, max(x) * ifelse(any(colours_RSI %in% cols_sub$cols), 1.1, 1)),
ylab = ylab,
xlab = xlab,
axes = FALSE)
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)
@@ -149,13 +156,14 @@ plot.mic <- function(x,
legend("top",
x.intersp = 0.5,
legend = translate_AMR(legend_txt, language = language),
legend = translate_into_language(legend_txt, language = language),
fill = legend_col,
horiz = TRUE,
cex = 0.75,
box.lwd = 0,
box.col = "#FFFFFF55",
bg = "#FFFFFF55")
bg = "#FFFFFF55"
)
}
}
@@ -166,7 +174,7 @@ barplot.mic <- function(height,
mo = NULL,
ab = NULL,
guideline = "EUCAST",
main = paste("MIC values of", deparse(substitute(height))),
main = deparse(substitute(height)),
ylab = "Frequency",
xlab = "Minimum Inhibitory Concentration (mg/L)",
colours_RSI = c("#ED553B", "#3CAEA3", "#F6D55C"),
@@ -185,15 +193,16 @@ barplot.mic <- function(height,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
main <- gsub(" +", " ", paste0(main, collapse = " "))
plot(x = height,
plot(
x = height,
main = main,
ylab = ylab,
xlab = xlab,
@@ -201,7 +210,8 @@ barplot.mic <- function(height,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
...)
...
)
}
#' @method autoplot mic
@@ -211,7 +221,7 @@ autoplot.mic <- function(object,
mo = NULL,
ab = NULL,
guideline = "EUCAST",
title = paste("MIC values of", deparse(substitute(object))),
title = deparse(substitute(object)),
ylab = "Frequency",
xlab = "Minimum Inhibitory Concentration (mg/L)",
colours_RSI = c("#ED553B", "#3CAEA3", "#F6D55C"),
@@ -231,10 +241,10 @@ autoplot.mic <- function(object,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if ("main" %in% names(list(...))) {
@@ -245,38 +255,46 @@ autoplot.mic <- function(object,
}
x <- plot_prepare_table(object, expand = expand)
cols_sub <- plot_colours_subtitle_guideline(x = x,
cols_sub <- plot_colours_subtitle_guideline(
x = x,
mo = mo,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
fn = as.mic,
language = language,
...)
...
)
df <- as.data.frame(x, stringsAsFactors = TRUE)
colnames(df) <- c("mic", "count")
df$cols <- cols_sub$cols
df$cols[df$cols == colours_RSI[1]] <- "Resistant"
df$cols[df$cols == colours_RSI[2]] <- "Susceptible"
df$cols[df$cols == colours_RSI[3]] <- plot_name_of_I(cols_sub$guideline)
df$cols <- factor(translate_AMR(df$cols, language = language),
levels = translate_AMR(c("Susceptible", plot_name_of_I(cols_sub$guideline), "Resistant"),
language = language),
ordered = TRUE)
df$cols <- factor(translate_into_language(df$cols, language = language),
levels = translate_into_language(c("Susceptible", plot_name_of_I(cols_sub$guideline), "Resistant"),
language = language
),
ordered = TRUE
)
p <- ggplot2::ggplot(df)
if (any(colours_RSI %in% cols_sub$cols)) {
vals <- c("Resistant" = colours_RSI[1],
vals <- c(
"Resistant" = colours_RSI[1],
"Susceptible" = colours_RSI[2],
"Susceptible, incr. exp." = colours_RSI[3],
"Intermediate" = colours_RSI[3])
names(vals) <- translate_AMR(names(vals), language = language)
"Intermediate" = colours_RSI[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,
ggplot2::scale_fill_manual(
values = vals,
name = NULL,
limits = force)
limits = force
)
} else {
p <- p +
ggplot2::geom_col(ggplot2::aes(x = mic, y = count))
@@ -290,8 +308,10 @@ autoplot.mic <- function(object,
#' @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"))
stats::setNames(
as.data.frame(plot_prepare_table(object, expand = FALSE)),
c("x", "y")
)
}
#' @method plot disk
@@ -299,7 +319,7 @@ fortify.mic <- function(object, ...) {
#' @importFrom graphics barplot axis mtext legend
#' @rdname plot
plot.disk <- function(x,
main = paste("Disk zones of", deparse(substitute(x))),
main = deparse(substitute(x)),
ylab = "Frequency",
xlab = "Disk diffusion diameter (mm)",
mo = NULL,
@@ -321,10 +341,10 @@ plot.disk <- function(x,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if (length(colours_RSI) == 1) {
@@ -334,14 +354,16 @@ plot.disk <- function(x,
x <- plot_prepare_table(x, expand = expand)
cols_sub <- plot_colours_subtitle_guideline(x = x,
cols_sub <- plot_colours_subtitle_guideline(
x = x,
mo = mo,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
fn = as.disk,
language = language,
...)
...
)
barplot(x,
col = cols_sub$cols,
@@ -349,7 +371,8 @@ plot.disk <- function(x,
ylim = c(0, max(x) * ifelse(any(colours_RSI %in% cols_sub$cols), 1.1, 1)),
ylab = ylab,
xlab = xlab,
axes = FALSE)
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)
@@ -372,13 +395,14 @@ plot.disk <- function(x,
}
legend("top",
x.intersp = 0.5,
legend = translate_AMR(legend_txt, language = language),
legend = translate_into_language(legend_txt, language = language),
fill = legend_col,
horiz = TRUE,
cex = 0.75,
box.lwd = 0,
box.col = "#FFFFFF55",
bg = "#FFFFFF55")
bg = "#FFFFFF55"
)
}
}
@@ -386,7 +410,7 @@ plot.disk <- function(x,
#' @export
#' @noRd
barplot.disk <- function(height,
main = paste("Disk zones of", deparse(substitute(height))),
main = deparse(substitute(height)),
ylab = "Frequency",
xlab = "Disk diffusion diameter (mm)",
mo = NULL,
@@ -408,15 +432,16 @@ barplot.disk <- function(height,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
main <- gsub(" +", " ", paste0(main, collapse = " "))
plot(x = height,
plot(
x = height,
main = main,
ylab = ylab,
xlab = xlab,
@@ -424,7 +449,8 @@ barplot.disk <- function(height,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
...)
...
)
}
#' @method autoplot disk
@@ -433,7 +459,7 @@ barplot.disk <- function(height,
autoplot.disk <- function(object,
mo = NULL,
ab = NULL,
title = paste("Disk zones of", deparse(substitute(object))),
title = deparse(substitute(object)),
ylab = "Frequency",
xlab = "Disk diffusion diameter (mm)",
guideline = "EUCAST",
@@ -454,10 +480,10 @@ autoplot.disk <- function(object,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if ("main" %in% names(list(...))) {
@@ -468,14 +494,16 @@ autoplot.disk <- function(object,
}
x <- plot_prepare_table(object, expand = expand)
cols_sub <- plot_colours_subtitle_guideline(x = x,
cols_sub <- plot_colours_subtitle_guideline(
x = x,
mo = mo,
ab = ab,
guideline = guideline,
colours_RSI = colours_RSI,
fn = as.disk,
language = language,
...)
...
)
df <- as.data.frame(x, stringsAsFactors = TRUE)
colnames(df) <- c("disk", "count")
df$cols <- cols_sub$cols
@@ -483,24 +511,30 @@ autoplot.disk <- function(object,
df$cols[df$cols == colours_RSI[1]] <- "Resistant"
df$cols[df$cols == colours_RSI[2]] <- "Susceptible"
df$cols[df$cols == colours_RSI[3]] <- plot_name_of_I(cols_sub$guideline)
df$cols <- factor(translate_AMR(df$cols, language = language),
levels = translate_AMR(c("Susceptible", plot_name_of_I(cols_sub$guideline), "Resistant"),
language = language),
ordered = TRUE)
df$cols <- factor(translate_into_language(df$cols, language = language),
levels = translate_into_language(c("Susceptible", plot_name_of_I(cols_sub$guideline), "Resistant"),
language = language
),
ordered = TRUE
)
p <- ggplot2::ggplot(df)
if (any(colours_RSI %in% cols_sub$cols)) {
vals <- c("Resistant" = colours_RSI[1],
vals <- c(
"Resistant" = colours_RSI[1],
"Susceptible" = colours_RSI[2],
"Susceptible, incr. exp." = colours_RSI[3],
"Intermediate" = colours_RSI[3])
names(vals) <- translate_AMR(names(vals), language = language)
"Intermediate" = colours_RSI[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,
ggplot2::scale_fill_manual(
values = vals,
name = NULL,
limits = force)
limits = force
)
} else {
p <- p +
ggplot2::geom_col(ggplot2::aes(x = disk, y = count))
@@ -514,8 +548,10 @@ autoplot.disk <- function(object,
#' @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"))
stats::setNames(
as.data.frame(plot_prepare_table(object, expand = FALSE)),
c("x", "y")
)
}
#' @method plot rsi
@@ -525,49 +561,65 @@ fortify.disk <- function(object, ...) {
plot.rsi <- function(x,
ylab = "Percentage",
xlab = "Antimicrobial Interpretation",
main = paste("Resistance Overview of", deparse(substitute(x))),
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)
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_into_language(xlab, language = language)
}
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(data, data.frame(x = "S", n = 0, s = 0, stringsAsFactors = FALSE),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
}
if (!"I" %in% data$x) {
data <- rbind(data, data.frame(x = "I", n = 0, s = 0, stringsAsFactors = FALSE),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
}
if (!"R" %in% data$x) {
data <- rbind(data, data.frame(x = "R", n = 0, s = 0, stringsAsFactors = FALSE),
stringsAsFactors = FALSE)
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,
plot(
x = data$x,
y = data$s,
lwd = 2,
ylim = c(0, ymax),
ylab = ylab,
xlab = xlab,
main = main,
axes = FALSE)
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,
text(
x = data$x,
y = data$s + 4,
labels = paste0(data$s, "% (n = ", data$n, ")"))
labels = paste0(data$s, "% (n = ", data$n, ")")
)
}
@@ -576,7 +628,7 @@ plot.rsi <- function(x,
#' @export
#' @noRd
barplot.rsi <- function(height,
main = paste("Resistance Overview of", deparse(substitute(height))),
main = deparse(substitute(height)),
xlab = "Antimicrobial Interpretation",
ylab = "Frequency",
colours_RSI = c("#ED553B", "#3CAEA3", "#F6D55C"),
@@ -592,10 +644,10 @@ barplot.rsi <- function(height,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if (length(colours_RSI) == 1) {
@@ -612,7 +664,8 @@ barplot.rsi <- function(height,
xlab = xlab,
main = main,
ylab = ylab,
axes = FALSE)
axes = FALSE
)
axis(2, seq(0, max(x)))
}
@@ -620,7 +673,7 @@ barplot.rsi <- function(height,
#' @rdname plot
# will be exported using s3_register() in R/zzz.R
autoplot.rsi <- function(object,
title = paste("Resistance Overview of", deparse(substitute(object))),
title = deparse(substitute(object)),
xlab = "Antimicrobial Interpretation",
ylab = "Frequency",
colours_RSI = c("#ED553B", "#3CAEA3", "#F6D55C"),
@@ -634,10 +687,10 @@ autoplot.rsi <- function(object,
# translate if not specifically set
if (missing(ylab)) {
ylab <- translate_AMR(ylab, language = language)
ylab <- translate_into_language(ylab, language = language)
}
if (missing(xlab)) {
xlab <- translate_AMR(xlab, language = language)
xlab <- translate_into_language(xlab, language = language)
}
if ("main" %in% names(list(...))) {
@@ -656,10 +709,14 @@ autoplot.rsi <- function(object,
ggplot2::ggplot(df) +
ggplot2::geom_col(ggplot2::aes(x = rsi, y = count, fill = rsi)) +
# limits = force is needed because of a ggplot2 >= 3.3.4 bug (#4511)
ggplot2::scale_fill_manual(values = c("R" = colours_RSI[1],
ggplot2::scale_fill_manual(
values = c(
"R" = colours_RSI[1],
"S" = colours_RSI[2],
"I" = colours_RSI[3]),
limits = force) +
"I" = colours_RSI[3]
),
limits = force
) +
ggplot2::labs(title = title, x = xlab, y = ylab) +
ggplot2::theme(legend.position = "none")
}
@@ -668,8 +725,10 @@ autoplot.rsi <- function(object,
#' @rdname plot
# will be exported using s3_register() in R/zzz.R
fortify.rsi <- function(object, ...) {
stats::setNames(as.data.frame(table(object)),
c("x", "y"))
stats::setNames(
as.data.frame(table(object)),
c("x", "y")
)
}
plot_prepare_table <- function(x, expand) {
@@ -734,13 +793,19 @@ plot_colours_subtitle_guideline <- function(x, mo, ab, guideline, colours_RSI, f
moname <- mo_name(mo, language = language)
abname <- ab_name(ab, language = language)
if (all(cols == "#BEBEBE")) {
message_("No ", guideline, " interpretations found for ",
ab_name(ab, language = NULL, tolower = TRUE), " in ", moname)
message_(
"No ", guideline, " interpretations found for ",
ab_name(ab, language = NULL, tolower = TRUE), " in ", moname
)
guideline_txt <- ""
} else {
guideline_txt <- paste0("(", guideline, ")")
guideline_txt <- guideline
if (isTRUE(list(...)$uti)) {
guideline_txt <- paste("UTIs,", guideline_txt)
}
sub <- bquote(.(abname)~"-"~italic(.(moname))~.(guideline_txt))
guideline_txt <- paste0("(", guideline_txt, ")")
}
sub <- bquote(.(abname) ~ "-" ~ italic(.(moname)) ~ .(guideline_txt))
} else {
cols <- "#BEBEBE"
sub <- NULL
+64 -36
View File
@@ -28,7 +28,6 @@
#' @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
#' @inheritSection lifecycle Stable Lifecycle
#' @param ... one or more vectors (or columns) with antibiotic interpretations. They will be transformed internally with [as.rsi()] 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%"`.
@@ -88,11 +87,11 @@
#' @aliases portion
#' @name proportion
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # example_isolates is a data set available in the AMR package.
#' ?example_isolates
#' # run ?example_isolates for more info.
#'
#' # base R ------------------------------------------------------------
#' resistance(example_isolates$AMX) # determines %R
#' susceptibility(example_isolates$AMX) # determines %S+I
#'
@@ -103,20 +102,25 @@
#' proportion_IR(example_isolates$AMX)
#' proportion_R(example_isolates$AMX)
#'
#' # dplyr -------------------------------------------------------------
#' \donttest{
#' if (require("dplyr")) {
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(r = resistance(CIP),
#' n = n_rsi(CIP)) # n_rsi works like n_distinct in dplyr, see ?n_rsi
#' group_by(ward) %>%
#' summarise(
#' r = resistance(CIP),
#' n = n_rsi(CIP)
#' ) # n_rsi works like n_distinct in dplyr, see ?n_rsi
#'
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(R = resistance(CIP, as_percent = TRUE),
#' 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_rsi(CIP), # same - analogous to n_distinct
#' total = n()) # NOT the number of tested isolates!
#' 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:
@@ -132,24 +136,30 @@
#'
#' # See Details on how `only_all_tested` works. Example:
#' example_isolates %>%
#' summarise(numerator = count_susceptible(AMC, GEN),
#' summarise(
#' numerator = count_susceptible(AMC, GEN),
#' denominator = count_all(AMC, GEN),
#' proportion = susceptibility(AMC, GEN))
#' proportion = susceptibility(AMC, GEN)
#' )
#'
#' example_isolates %>%
#' summarise(numerator = count_susceptible(AMC, GEN, only_all_tested = TRUE),
#' 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))
#' proportion = susceptibility(AMC, GEN, only_all_tested = TRUE)
#' )
#'
#'
#' example_isolates %>%
#' group_by(hospital_id) %>%
#' summarise(cipro_p = susceptibility(CIP, as_percent = TRUE),
#' 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))
#' combination_n = count_all(CIP, GEN)
#' )
#'
#' # Get proportions S/I/R immediately of all rsi columns
#' example_isolates %>%
@@ -157,10 +167,11 @@
#' proportion_df(translate = FALSE)
#'
#' # It also supports grouping variables
#' # (use rsi_df to also include the count)
#' example_isolates %>%
#' select(hospital_id, AMX, CIP) %>%
#' group_by(hospital_id) %>%
#' proportion_df(translate = FALSE)
#' select(ward, AMX, CIP) %>%
#' group_by(ward) %>%
#' rsi_df(translate = FALSE)
#' }
#' }
resistance <- function(...,
@@ -173,8 +184,10 @@ resistance <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -189,8 +202,10 @@ susceptibility <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -205,8 +220,10 @@ proportion_R <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -221,8 +238,10 @@ proportion_IR <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -237,8 +256,10 @@ proportion_I <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -253,8 +274,10 @@ proportion_SI <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -269,8 +292,10 @@ proportion_S <- function(...,
minimum = minimum,
as_percent = as_percent,
only_all_tested = only_all_tested,
only_count = FALSE),
error = function(e) stop_(e$message, call = -5))
only_count = FALSE
),
error = function(e) stop_(e$message, call = -5)
)
}
#' @rdname proportion
@@ -283,7 +308,8 @@ proportion_df <- function(data,
combine_SI = TRUE,
combine_IR = FALSE) {
tryCatch(
rsi_calc_df(type = "proportion",
rsi_calc_df(
type = "proportion",
data = data,
translate_ab = translate_ab,
language = language,
@@ -291,6 +317,8 @@ proportion_df <- function(data,
as_percent = as_percent,
combine_SI = combine_SI,
combine_IR = combine_IR,
combine_SI_missing = missing(combine_SI)),
error = function(e) stop_(e$message, call = -5))
combine_SI_missing = missing(combine_SI)
),
error = function(e) stop_(e$message, call = -5)
)
}
+27 -20
View File
@@ -26,7 +26,6 @@
#' Random MIC Values/Disk Zones/RSI 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 agent, the generated results will reflect reality as much as possible.
#' @inheritSection lifecycle Stable Lifecycle
#' @param size desired size of the returned vector. If used in a [data.frame] call or `dplyr` verb, will get the current (group) size if left blank.
#' @param mo any [character] that can be coerced to a valid microorganism code with [as.mo()]
#' @param ab any [character] that can be coerced to a valid antimicrobial agent code with [as.ab()]
@@ -34,26 +33,25 @@
#' @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 latest EUCAST guideline implemented in the [rsi_translation] data set. To create specific generated values per bug or drug, set the `mo` and/or `ab` argument.
#' Generated values are based on the EUCAST `r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))` guideline as implemented in the [rsi_translation] 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
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' random_mic(100)
#' random_disk(100)
#' random_rsi(100)
#' random_mic(25)
#' random_disk(25)
#' random_rsi(25)
#'
#' \donttest{
#' # make the random generation more realistic by setting a bug and/or drug:
#' random_mic(100, "Klebsiella pneumoniae") # range 0.0625-64
#' random_mic(100, "Klebsiella pneumoniae", "meropenem") # range 0.0625-16
#' random_mic(100, "Streptococcus pneumoniae", "meropenem") # range 0.0625-4
#' 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(100, "Klebsiella pneumoniae") # range 8-50
#' random_disk(100, "Klebsiella pneumoniae", "ampicillin") # range 11-17
#' random_disk(100, "Streptococcus pneumoniae", "ampicillin") # range 12-27
#' 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)
@@ -89,6 +87,7 @@ random_rsi <- function(size = NULL, prob_RSI = c(0.33, 0.33, 0.33), ...) {
}
random_exec <- function(type, size, mo = NULL, ab = NULL) {
check_dataset_integrity()
df <- rsi_translation %pm>%
pm_filter(guideline %like% "EUCAST") %pm>%
pm_arrange(pm_desc(guideline)) %pm>%
@@ -97,10 +96,12 @@ random_exec <- function(type, size, mo = NULL, ab = NULL) {
if (!is.null(mo)) {
mo_coerced <- as.mo(mo)
mo_include <- c(mo_coerced,
mo_include <- c(
mo_coerced,
as.mo(mo_genus(mo_coerced)),
as.mo(mo_family(mo_coerced)),
as.mo(mo_order(mo_coerced)))
as.mo(mo_order(mo_coerced))
)
df_new <- df %pm>%
subset(mo %in% mo_include)
if (nrow(df_new) > 0) {
@@ -126,10 +127,14 @@ random_exec <- function(type, size, mo = NULL, ab = NULL) {
mic_range <- c(0.001, 0.002, 0.005, 0.010, 0.025, 0.0625, 0.125, 0.250, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256)
# get highest/lowest +/- random 1 to 3 higher factors of two
max_range <- mic_range[min(length(mic_range),
which(mic_range == max(df$breakpoint_R)) + sample(c(1:3), 1))]
min_range <- mic_range[max(1,
which(mic_range == min(df$breakpoint_S)) - sample(c(1:3), 1))]
max_range <- mic_range[min(
length(mic_range),
which(mic_range == max(df$breakpoint_R)) + sample(c(1:3), 1)
)]
min_range <- mic_range[max(
1,
which(mic_range == min(df$breakpoint_S)) - sample(c(1:3), 1)
)]
mic_range_new <- mic_range[mic_range <= max_range & mic_range >= min_range]
if (length(mic_range_new) == 0) {
@@ -145,9 +150,11 @@ random_exec <- function(type, size, mo = NULL, ab = NULL) {
}
return(out)
} else if (type == "DISK") {
set_range <- seq(from = as.integer(min(df$breakpoint_R) / 1.25),
set_range <- seq(
from = as.integer(min(df$breakpoint_R) / 1.25),
to = as.integer(max(df$breakpoint_S) * 1.25),
by = 1)
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)
+67 -62
View File
@@ -26,7 +26,6 @@
#' 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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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, defaults to the first column of with a date class
@@ -34,7 +33,7 @@
#' @param year_max highest year to use in the prediction model, defaults to 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 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.
@@ -64,12 +63,12 @@
#' @rdname resistance_predict
#' @export
#' @importFrom stats predict glm lm
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' x <- resistance_predict(example_isolates,
#' col_ab = "AMX",
#' year_min = 2010,
#' model = "binomial")
#' model = "binomial"
#' )
#' plot(x)
#' \donttest{
#' if (require("ggplot2")) {
@@ -82,7 +81,7 @@
#' filter_first_isolate() %>%
#' filter(mo_genus(mo) == "Staphylococcus") %>%
#' resistance_predict("PEN", model = "binomial")
#' plot(x)
#' print(plot(x))
#'
#' # get the model from the object
#' mymodel <- attributes(x)$model
@@ -90,33 +89,18 @@
#' }
#'
#' # create nice plots with ggplot2 yourself
#' if (require("dplyr") & require("ggplot2")) {
#'
#' if (require("dplyr") && require("ggplot2")) {
#' data <- example_isolates %>%
#' filter(mo == as.mo("E. coli")) %>%
#' resistance_predict(col_ab = "AMX",
#' resistance_predict(
#' col_ab = "AMX",
#' col_date = "date",
#' model = "binomial",
#' info = FALSE,
#' minimum = 15)
#'
#' minimum = 15
#' )
#' head(data)
#' autoplot(data)
#'
#' ggplot(data,
#' aes(x = year)) +
#' geom_col(aes(y = value),
#' fill = "grey75") +
#' geom_errorbar(aes(ymin = se_min,
#' ymax = se_max),
#' colour = "grey50") +
#' scale_y_continuous(limits = c(0, 1),
#' breaks = seq(0, 1, 0.1),
#' labels = paste0(seq(0, 100, 10), "%")) +
#' labs(title = expression(paste("Forecast of Amoxicillin Resistance in ",
#' italic("E. coli"))),
#' y = "%R",
#' x = "Year") +
#' theme_minimal(base_size = 13)
#' }
#' }
resistance_predict <- function(x,
@@ -145,6 +129,9 @@ resistance_predict <- function(x,
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)
dots <- unlist(list(...))
if (length(dots) != 0) {
# backwards compatibility with old arguments
@@ -162,11 +149,10 @@ resistance_predict <- function(x,
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")
# no grouped tibbles
x <- as.data.frame(x, stringsAsFactors = FALSE)
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
@@ -191,8 +177,9 @@ resistance_predict <- function(x,
# 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)])),
stringsAsFactors = FALSE)
df <- as.data.frame(rbind(table(df[, c("year", col_ab), drop = FALSE])),
stringsAsFactors = FALSE
)
df$year <- as.integer(rownames(df))
rownames(df) <- NULL
@@ -227,7 +214,6 @@ resistance_predict <- function(x,
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))
@@ -240,7 +226,6 @@ resistance_predict <- function(x,
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))
@@ -253,23 +238,23 @@ resistance_predict <- function(x,
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),
df_prediction <- data.frame(
year = unlist(years),
value = prediction,
se_min = prediction - se,
se_max = prediction + se,
stringsAsFactors = FALSE)
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 <- ifelse(df_prediction$se_max > 1, 1, df_prediction$se_max)
@@ -277,10 +262,12 @@ resistance_predict <- function(x,
# se_min not below 0
df_prediction$se_min <- ifelse(df_prediction$se_min < 0, 0, df_prediction$se_min)
df_observations <- data.frame(year = df$year,
df_observations <- data.frame(
year = df$year,
observations = df$R + df$S,
observed = df$R / (df$R + df$S),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
df_prediction <- df_prediction %pm>%
pm_left_join(df_observations, by = "year")
df_prediction$estimated <- df_prediction$value
@@ -293,11 +280,11 @@ resistance_predict <- function(x,
}
df_prediction$value <- ifelse(df_prediction$value > 1, 1, ifelse(df_prediction$value < 0, 0, df_prediction$value))
df_prediction <- df_prediction[order(df_prediction$year), ]
df_prediction <- df_prediction[order(df_prediction$year), , drop = FALSE]
structure(
.Data = df_prediction,
class = c("resistance_predict", "data.frame"),
out <- as_original_data_class(df_prediction, class(x.bak))
structure(out,
class = c("resistance_predict", class(out)),
I_as_S = I_as_S,
model_title = model,
model = model_lm,
@@ -323,7 +310,8 @@ plot.resistance_predict <- function(x, main = paste("Resistance Prediction of",
ylab <- "%IR"
}
plot(x = x$year,
plot(
x = x$year,
y = x$value,
ylim = c(0, 1),
yaxt = "n", # no y labels
@@ -331,25 +319,32 @@ plot.resistance_predict <- function(x, main = paste("Resistance Prediction of",
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)
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,
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)
length = 0.05, angle = 90, code = 3, lwd = 1.5
)
# overlay grey points for prediction
points(x = subset(x, is.na(observations))$year,
points(
x = subset(x, is.na(observations))$year,
y = subset(x, is.na(observations))$value,
pch = 19,
col = "grey40")
col = "grey40"
)
}
#' @rdname resistance_predict
@@ -371,16 +366,24 @@ ggplot_rsi_predict <- function(x,
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) +
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,
ggplot2::labs(
title = main,
y = paste0("Percentage (", ylab, ")"),
x = "Year",
caption = paste0("(n = ", sum(x$observations, na.rm = TRUE),
", model: ", attributes(x)$model_title, ")"))
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)
@@ -389,9 +392,11 @@ ggplot_rsi_predict <- function(x,
}
p <- p +
# overlay grey points for prediction
ggplot2::geom_point(data = subset(x, is.na(observations)),
ggplot2::geom_point(
data = subset(x, is.na(observations)),
size = 2,
colour = "grey40")
colour = "grey40"
)
p
}
+211 -117
View File
@@ -26,14 +26,13 @@
#' Interpret MIC and Disk Values, or Clean Raw R/SI Data
#'
#' Interpret minimum inhibitory concentration (MIC) values and disk diffusion diameters according to EUCAST or CLSI, or clean up existing R/SI values. This transforms the input to a new class [`rsi`], which is an ordered [factor] with levels `S < I < R`.
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname as.rsi
#' @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 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.rsi()] 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 the latest included EUCAST guideline, see *Details* for all options
#' @param guideline defaults to EUCAST `r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))` (the latest implemented EUCAST guideline in the [rsi_translation] data set), supports EUCAST (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "EUCAST")$guideline)))`) and CLSI (`r min(as.integer(gsub("[^0-9]", "", subset(rsi_translation, guideline %like% "CLSI")$guideline)))`-`r max(as.integer(gsub("[^0-9]", "", subset(rsi_translation, 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 reference_data a [data.frame] to be used for interpretation, which defaults to the [rsi_translation] 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 [rsi_translation] data set (same column names and column types). Please note that the `guideline` argument will be ignored when `reference_data` is manually set.
@@ -98,37 +97,38 @@
#' @export
#' @seealso [as.mic()], [as.disk()], [as.mo()]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' example_isolates
#' summary(example_isolates) # see all R/SI results at a glance
#' \donttest{
#' if (require("skimr")) {
#' # class <rsi> supported in skim() too:
#' skim(example_isolates)
#' }
#' }
#'
#' # 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",
#' df <- data.frame(
#' microorganism = "Escherichia coli",
#' AMP = as.mic(8),
#' CIP = as.mic(0.256),
#' GEN = as.disk(18),
#' TOB = as.disk(16),
#' NIT = as.mic(32),
#' ERY = "R")
#' ERY = "R"
#' )
#' as.rsi(df)
#'
#' # for single values
#' as.rsi(x = as.mic(2),
#' as.rsi(
#' x = as.mic(2),
#' mo = as.mo("S. pneumoniae"),
#' ab = "AMP",
#' guideline = "EUCAST")
#' guideline = "EUCAST"
#' )
#'
#' as.rsi(x = as.disk(18),
#' as.rsi(
#' x = as.disk(18),
#' mo = "Strep pneu", # `mo` will be coerced with as.mo()
#' ab = "ampicillin", # and `ab` with as.ab()
#' guideline = "EUCAST")
#' guideline = "EUCAST"
#' )
#'
#' \donttest{
#' # the dplyr way
@@ -143,14 +143,18 @@
#' mutate_at(vars(AMP:TOB), as.rsi, mo = .$microorganism)
#'
#' # to include information about urinary tract infections (UTI)
#' data.frame(mo = "E. coli",
#' data.frame(
#' mo = "E. coli",
#' NIT = c("<= 2", 32),
#' from_the_bladder = c(TRUE, FALSE)) %>%
#' from_the_bladder = c(TRUE, FALSE)
#' ) %>%
#' as.rsi(uti = "from_the_bladder")
#'
#' data.frame(mo = "E. coli",
#' data.frame(
#' mo = "E. coli",
#' NIT = c("<= 2", 32),
#' specimen = c("urine", "blood")) %>%
#' specimen = c("urine", "blood")
#' ) %>%
#' as.rsi() # automatically determines urine isolates
#'
#' df %>%
@@ -161,7 +165,6 @@
#'
#' as.rsi(c("S", "I", "R", "A", "B", "C"))
#' as.rsi("<= 0.002; S") # will return "S"
#' rsi_data <- as.rsi(c(rep("S", 474), rep("I", 36), rep("R", 370)))
#' is.rsi(rsi_data)
#' plot(rsi_data) # for percentages
@@ -179,7 +182,7 @@
#' example_isolates %>%
#' mutate_if(is.rsi.eligible, as.rsi)
#'
#' # note: from dplyr 1.0.0 on, this will be:
#' # since dplyr 1.0.0, this can also be:
#' # example_isolates %>%
#' # mutate(across(where(is.rsi.eligible), as.rsi))
#' }
@@ -189,10 +192,11 @@ as.rsi <- function(x, ...) {
}
#' @rdname as.rsi
#' @details `NA_rsi_` is a missing value of the new `<rsi>` class.
#' @details `NA_rsi_` is a missing value of the new `<rsi>` class, analogous to e.g. base \R's [`NA_character_`][base::NA].
#' @export
NA_rsi_ <- set_clean_class(factor(NA, levels = c("S", "I", "R"), ordered = TRUE),
new_class = c("rsi", "ordered", "factor"))
new_class = c("rsi", "ordered", "factor")
)
#' @rdname as.rsi
#' @export
@@ -215,7 +219,8 @@ is.rsi.eligible <- function(x, threshold = 0.05) {
}
stop_if(NCOL(x) > 1, "`x` must be a one-dimensional vector.")
if (any(c("numeric",
if (any(c(
"numeric",
"integer",
"mo",
"ab",
@@ -224,7 +229,8 @@ is.rsi.eligible <- function(x, threshold = 0.05) {
"raw",
"hms",
"mic",
"disk")
"disk"
)
%in% class(x))) {
# no transformation needed
return(FALSE)
@@ -241,8 +247,10 @@ is.rsi.eligible <- function(x, threshold = 0.05) {
ab <- suppressWarnings(as.ab(cur_col, fast_mode = TRUE, info = FALSE))
if (!is.na(ab)) {
# this is a valid antibiotic code
message_("Column '", font_bold(cur_col), "' is as.rsi()-eligible (despite only having empty values), since it seems to be ",
ab_name(ab, language = NULL, tolower = TRUE), " (", ab, ")")
message_(
"Column '", font_bold(cur_col), "' is as.rsi()-eligible (despite only having empty values), since it seems to be ",
ab_name(ab, language = NULL, tolower = TRUE), " (", ab, ")"
)
return(TRUE)
}
}
@@ -278,9 +286,7 @@ as.rsi.default <- function(x, ...) {
x[x.bak == 2] <- "I"
x[x.bak == 3] <- "R"
}
} else if (!all(is.na(x)) && !identical(levels(x), c("R", "S", "I")) && !all(x %in% c("R", "S", "I", NA))) {
if (all(x %unlike% "(R|S|I)", na.rm = TRUE)) {
# check if they are actually MICs or disks
if (all_valid_mics(x)) {
@@ -297,12 +303,18 @@ as.rsi.default <- function(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)]])
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)
@@ -336,7 +348,9 @@ as.rsi.default <- function(x, ...) {
warning_("in `as.rsi()`: ", na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid antimicrobial interpretations: ",
list_missing, call = FALSE)
list_missing,
call = FALSE
)
}
if (any(toupper(x.bak[!is.na(x.bak)]) == "U") && message_not_thrown_before("as.rsi", "U")) {
warning_("in `as.rsi()`: 'U' was interpreted as 'S', following some laboratory systems")
@@ -351,7 +365,8 @@ as.rsi.default <- function(x, ...) {
}
set_clean_class(factor(x, levels = c("S", "I", "R"), ordered = TRUE),
new_class = c("rsi", "ordered", "factor"))
new_class = c("rsi", "ordered", "factor")
)
}
#' @rdname as.rsi
@@ -365,7 +380,8 @@ as.rsi.mic <- function(x,
add_intrinsic_resistance = FALSE,
reference_data = AMR::rsi_translation,
...) {
as_rsi_method(method_short = "mic",
as_rsi_method(
method_short = "mic",
method_long = "MIC values",
x = x,
mo = mo,
@@ -375,7 +391,8 @@ as.rsi.mic <- function(x,
conserve_capped_values = conserve_capped_values,
add_intrinsic_resistance = add_intrinsic_resistance,
reference_data = reference_data,
...)
...
)
}
#' @rdname as.rsi
@@ -388,7 +405,8 @@ as.rsi.disk <- function(x,
add_intrinsic_resistance = FALSE,
reference_data = AMR::rsi_translation,
...) {
as_rsi_method(method_short = "disk",
as_rsi_method(
method_short = "disk",
method_long = "disk diffusion zones",
x = x,
mo = mo,
@@ -398,7 +416,8 @@ as.rsi.disk <- function(x,
conserve_capped_values = FALSE,
add_intrinsic_resistance = add_intrinsic_resistance,
reference_data = reference_data,
...)
...
)
}
#' @rdname as.rsi
@@ -448,8 +467,10 @@ as.rsi.data.frame <- function(x,
}
} 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`")
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 {
@@ -463,11 +484,13 @@ as.rsi.data.frame <- function(x,
} else {
plural <- c("", "s", "a ")
}
message_("Assuming value", plural[1], " ",
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.rsi(uti = FALSE)` to prevent this.")
".\n Use `as.rsi(uti = FALSE)` to prevent this."
)
} else {
# no data about UTI's found
uti <- FALSE
@@ -507,8 +530,10 @@ as.rsi.data.frame <- function(x,
}
})]
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.")
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"
@@ -528,7 +553,8 @@ as.rsi.data.frame <- function(x,
for (i in seq_len(length(ab_cols))) {
if (types[i] == "mic") {
x[, ab_cols[i]] <- as.rsi(x = x %pm>%
x[, ab_cols[i]] <- as.rsi(
x = x %pm>%
pm_pull(ab_cols[i]) %pm>%
as.character() %pm>%
as.mic(),
@@ -539,9 +565,11 @@ as.rsi.data.frame <- function(x,
conserve_capped_values = conserve_capped_values,
add_intrinsic_resistance = add_intrinsic_resistance,
reference_data = reference_data,
is_data.frame = TRUE)
is_data.frame = TRUE
)
} else if (types[i] == "disk") {
x[, ab_cols[i]] <- as.rsi(x = x %pm>%
x[, ab_cols[i]] <- as.rsi(
x = x %pm>%
pm_pull(ab_cols[i]) %pm>%
as.character() %pm>%
as.disk(),
@@ -551,7 +579,8 @@ as.rsi.data.frame <- function(x,
uti = uti,
add_intrinsic_resistance = add_intrinsic_resistance,
reference_data = reference_data,
is_data.frame = TRUE)
is_data.frame = TRUE
)
} else if (types[i] == "rsi") {
show_message <- FALSE
ab <- ab_cols[i]
@@ -563,7 +592,8 @@ as.rsi.data.frame <- function(x,
ifelse(ab_coerced != toupper(ab), paste0(ab_coerced, ", "), ""),
ab_name(ab_coerced, tolower = TRUE), ")... ",
appendLF = FALSE,
as_note = FALSE)
as_note = FALSE
)
} else if (!is.rsi(x.bak[, ab_cols[i], drop = TRUE])) {
show_message <- TRUE
# only print message if class not already set
@@ -571,7 +601,8 @@ as.rsi.data.frame <- function(x,
ifelse(ab_coerced != toupper(ab), paste0(ab_coerced, ", "), ""),
ab_name(ab_coerced, tolower = TRUE), ")... ",
appendLF = FALSE,
as_note = FALSE)
as_note = FALSE
)
}
x[, ab_cols[i]] <- as.rsi.default(x = as.character(x[, ab_cols[i], drop = TRUE]))
if (show_message == TRUE) {
@@ -598,23 +629,25 @@ get_guideline <- function(guideline, reference_data) {
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)
"'.\nValid guidelines are: ", vector_and(reference_data$guideline, quotes = TRUE, reverse = TRUE),
call = FALSE
)
guideline_param
}
as_rsi_method <- function(method_short = "mic",
method_long = "MIC values",
x = x,
mo = NULL,
ab = deparse(substitute(x)),
guideline = "EUCAST",
uti = FALSE,
conserve_capped_values = FALSE,
add_intrinsic_resistance = FALSE,
reference_data = AMR::rsi_translation,
as_rsi_method <- function(method_short,
method_long,
x,
mo,
ab,
guideline,
uti,
conserve_capped_values,
add_intrinsic_resistance,
reference_data,
...) {
meet_criteria(x)
meet_criteria(x, allow_NA = TRUE)
meet_criteria(mo, allow_class = c("mo", "character"), allow_NULL = TRUE)
meet_criteria(ab, allow_class = c("ab", "character"))
meet_criteria(guideline, allow_class = "character", has_length = 1)
@@ -629,34 +662,43 @@ as_rsi_method <- function(method_short = "mic",
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)
error = function(e) ab
)
}
# for auto-determining mo
mo_var_found <- ""
if (is.null(mo)) {
tryCatch({
tryCatch(
{
df <- get_current_data(arg_name = "mo", call = -3) # will return an error if not found
mo <- NULL
try({
try(
{
mo <- suppressMessages(search_type_in_df(df, "mo"))
}, silent = TRUE)
},
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) {
},
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.rsi.\n\n",
"To transform certain columns with e.g. mutate(), use `data %>% mutate(across(..., as.rsi, mo = x))`, where x is your column with microorganisms.\n",
"To tranform all ", method_long, " in a data set, use `data %>% as.rsi()` or `data %>% mutate(across(where(is.", method_short, "), as.rsi))`.", call = FALSE)
"To tranform all ", method_long, " in a data set, use `data %>% as.rsi()` or `data %>% mutate(across(where(is.", method_short, "), as.rsi))`.",
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.rsi.', call = FALSE)
stop_("No unambiguous name was supplied about the antibiotic (argument `ab`). See ?as.rsi.", call = FALSE)
}
ab_coerced <- suppressWarnings(as.ab(ab))
@@ -666,7 +708,8 @@ as_rsi_method <- function(method_short = "mic",
message_("Returning NAs for unknown drug: '", font_bold(ab),
"'. Rename this column to a drug name or code, and check the output with `as.ab()`.",
add_fn = font_red,
as_note = FALSE)
as_note = FALSE
)
return(as.rsi(rep(NA, length(x))))
}
if (length(mo_coerced) == 1) {
@@ -679,18 +722,26 @@ as_rsi_method <- function(method_short = "mic",
agent_formatted <- paste0("'", font_bold(ab), "'")
agent_name <- ab_name(ab_coerced, tolower = TRUE, language = NULL)
if (generalise_antibiotic_name(ab) != generalise_antibiotic_name(agent_name)) {
agent_formatted <- paste0(agent_formatted, " (", ab_coerced, ", ", agent_name, ")")
agent_formatted <- paste0(
agent_formatted,
" (", ifelse(ab == ab_coerced, "",
paste0(ab_coerced, ", ")
), agent_name, ")"
)
}
message_("=> Interpreting ", method_long, " of ", ifelse(isTRUE(list(...)$is_data.frame), "column ", ""),
agent_formatted,
mo_var_found,
" according to ", ifelse(identical(reference_data, AMR::rsi_translation),
font_bold(guideline_coerced),
"manually defined 'reference_data'"),
"manually defined 'reference_data'"
),
"... ",
appendLF = FALSE,
as_note = FALSE)
result <- exec_as.rsi(method = method_short,
as_note = FALSE
)
result <- exec_as.rsi(
method = method_short,
x = x,
mo = mo_coerced,
ab = ab_coerced,
@@ -698,7 +749,8 @@ as_rsi_method <- function(method_short = "mic",
uti = uti,
conserve_capped_values = conserve_capped_values,
add_intrinsic_resistance = add_intrinsic_resistance,
reference_data = reference_data) # exec_as.rsi will return message 'OK'
reference_data = reference_data
) # exec_as.rsi will return message 'OK'
result
}
@@ -745,39 +797,57 @@ exec_as.rsi <- function(method,
guideline_coerced <- get_guideline(guideline, reference_data)
if (guideline_coerced != guideline) {
if (message_not_thrown_before("as.rsi", "msg1")) {
if (message_not_thrown_before("as.rsi", "guideline")) {
message_("Using guideline ", font_bold(guideline_coerced), " as input for `guideline`.")
}
}
new_rsi <- rep(NA_character_, length(x))
ab_param <- ab
if (identical(reference_data, AMR::rsi_translation)) {
trans <- reference_data %pm>%
subset(guideline == guideline_coerced & method == method_param & ab == ab_param)
if (ab_param == "AMX" && nrow(trans) == 0) {
ab_param <- "AMP"
if (message_not_thrown_before("as.rsi", "AMP_for_AMX")) {
message_("(using ampicillin rules)", appendLF = FALSE, as_note = FALSE)
}
trans <- reference_data %pm>%
subset(guideline == guideline_coerced & method == method_param & ab == ab_param)
}
} else {
trans <- reference_data %pm>%
subset(method == method_param & ab == ab_param)
}
if (nrow(trans) == 0) {
message_(" OK.", add_fn = list(font_green, font_bold), as_note = FALSE)
load_mo_failures_uncertainties_renamed(metadata_mo)
return(set_clean_class(factor(new_rsi, levels = c("S", "I", "R"), ordered = TRUE),
new_class = c("rsi", "ordered", "factor")
))
}
trans$lookup <- paste(trans$mo, trans$ab)
lookup_mo <- paste(mo, ab)
lookup_genus <- paste(mo_genus, ab)
lookup_family <- paste(mo_family, ab)
lookup_order <- paste(mo_order, ab)
lookup_becker <- paste(mo_becker, ab)
lookup_lancefield <- paste(mo_lancefield, ab)
lookup_other <- paste(mo_other, ab)
lookup_mo <- paste(mo, ab_param)
lookup_genus <- paste(mo_genus, ab_param)
lookup_family <- paste(mo_family, ab_param)
lookup_order <- paste(mo_order, ab_param)
lookup_becker <- paste(mo_becker, ab_param)
lookup_lancefield <- paste(mo_lancefield, ab_param)
lookup_other <- paste(mo_other, ab_param)
any_is_intrinsic_resistant <- FALSE
for (i in seq_len(length(x))) {
is_intrinsic_r <- paste(mo[i], ab) %in% INTRINSIC_R
is_intrinsic_r <- paste(mo[i], ab_param) %in% INTRINSIC_R
any_is_intrinsic_resistant <- any_is_intrinsic_resistant | is_intrinsic_r
if (isTRUE(add_intrinsic_resistance) & is_intrinsic_r) {
if (guideline_coerced %unlike% "EUCAST") {
if (message_not_thrown_before("as.rsi", "msg2")) {
if (message_not_thrown_before("as.rsi", "intrinsic")) {
warning_("in `as.rsi()`: using 'add_intrinsic_resistance' is only useful when using EUCAST guidelines, since the rules for intrinsic resistance are based on EUCAST.")
}
} else {
@@ -788,16 +858,18 @@ exec_as.rsi <- function(method,
get_record <- trans %pm>%
# no subsetting to UTI here
subset(lookup %in% c(lookup_mo[i],
subset(lookup %in% c(
lookup_mo[i],
lookup_genus[i],
lookup_family[i],
lookup_order[i],
lookup_becker[i],
lookup_lancefield[i],
lookup_other[i]))
lookup_other[i]
))
if (any(get_record$uti == TRUE, na.rm = TRUE) && message_not_thrown_before("as.rsi", "msg3", ab)) {
warning_("in `as.rsi()`: interpretation of ", font_bold(ab_name(ab, tolower = TRUE)), " is only available for (uncomplicated) urinary tract infections (UTI) for some microorganisms. Use argument `uti` to set which isolates are from urine. See ?as.rsi.")
if (any(get_record$uti == TRUE, na.rm = TRUE) && !any(uti == TRUE, na.rm = TRUE) && message_not_thrown_before("as.rsi", "uti", ab_param)) {
warning_("in `as.rsi()`: interpretation of ", font_bold(ab_name(ab_param, tolower = TRUE)), " is only available for (uncomplicated) urinary tract infections (UTI) for some microorganisms. Use argument `uti` to set which isolates are from urine. See ?as.rsi.")
rise_warning <- TRUE
}
@@ -818,38 +890,47 @@ exec_as.rsi <- function(method,
if (is.na(x[i]) | (is.na(get_record$breakpoint_S) & is.na(get_record$breakpoint_R))) {
new_rsi[i] <- NA_character_
} else if (method == "mic") {
new_rsi[i] <- quick_case_when(isTRUE(conserve_capped_values) & x[i] %like% "^<[0-9]" ~ "S",
isTRUE(conserve_capped_values) & x[i] %like% "^>[0-9]" ~ "R",
new_rsi[i] <- quick_case_when(
isTRUE(conserve_capped_values) & isTRUE(x[i] %like% "^<[0-9]") ~ "S",
isTRUE(conserve_capped_values) & isTRUE(x[i] %like% "^>[0-9]") ~ "R",
# these basically call `<=.mic()` and `>=.mic()`:
x[i] <= get_record$breakpoint_S ~ "S",
x[i] >= get_record$breakpoint_R ~ "R",
isTRUE(x[i] <= get_record$breakpoint_S) ~ "S",
guideline_coerced %like% "EUCAST" & isTRUE(x[i] > get_record$breakpoint_R) ~ "R",
guideline_coerced %like% "CLSI" & isTRUE(x[i] >= get_record$breakpoint_R) ~ "R",
# return "I" when not match the bottom or top
!is.na(get_record$breakpoint_S) & !is.na(get_record$breakpoint_R) ~ "I",
# and NA otherwise
TRUE ~ NA_character_)
TRUE ~ NA_character_
)
} else if (method == "disk") {
new_rsi[i] <- quick_case_when(isTRUE(as.double(x[i]) >= as.double(get_record$breakpoint_S)) ~ "S",
isTRUE(as.double(x[i]) <= as.double(get_record$breakpoint_R)) ~ "R",
new_rsi[i] <- quick_case_when(
isTRUE(as.double(x[i]) >= as.double(get_record$breakpoint_S)) ~ "S",
guideline_coerced %like% "EUCAST" & isTRUE(as.double(x[i]) < as.double(get_record$breakpoint_R)) ~ "R",
guideline_coerced %like% "CLSI" & isTRUE(as.double(x[i]) <= as.double(get_record$breakpoint_R)) ~ "R",
# return "I" when not match the bottom or top
!is.na(get_record$breakpoint_S) & !is.na(get_record$breakpoint_R) ~ "I",
# and NA otherwise
TRUE ~ NA_character_)
TRUE ~ NA_character_
)
}
}
}
if (any_is_intrinsic_resistant & guideline_coerced %like% "EUCAST" & !isTRUE(add_intrinsic_resistance)) {
# found some intrinsic resistance, but was not applied
if (message_not_thrown_before("as.rsi", "msg4")) {
if (message_not_thrown_before("as.rsi", "unapplied_instrinsic")) {
warning_("in `as.rsi()`: found intrinsic resistance in some bug/drug combinations, although it was not applied.\nUse `as.rsi(..., add_intrinsic_resistance = TRUE)` to apply it.")
}
rise_warning <- TRUE
}
new_rsi <- x_bak %pm>%
pm_left_join(data.frame(x_mo = paste0(x, mo), new_rsi,
stringsAsFactors = FALSE),
by = "x_mo") %pm>%
pm_left_join(data.frame(
x_mo = paste0(x, mo), new_rsi,
stringsAsFactors = FALSE
),
by = "x_mo"
) %pm>%
pm_pull(new_rsi)
if (isTRUE(rise_warning)) {
@@ -861,7 +942,8 @@ exec_as.rsi <- function(method,
load_mo_failures_uncertainties_renamed(metadata_mo)
set_clean_class(factor(new_rsi, levels = c("S", "I", "R"), ordered = TRUE),
new_class = c("rsi", "ordered", "factor"))
new_class = c("rsi", "ordered", "factor")
)
}
# will be exported using s3_register() in R/zzz.R
@@ -889,12 +971,14 @@ freq.rsi <- function(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),
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]
}
))[1L]
}
ab <- suppressMessages(suppressWarnings(as.ab(x_name)))
digits <- list(...)$digits
@@ -902,17 +986,25 @@ freq.rsi <- function(x, ...) {
digits <- 2
}
if (!is.na(ab)) {
cleaner::freq.default(x = x, ...,
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))))
digits = digits
))
)
)
} else {
cleaner::freq.default(x = x, ...,
cleaner::freq.default(
x = x, ...,
.add_header = list(
`%SI` = trimws(percentage(susceptibility(x, minimum = 0, as_percent = FALSE),
digits = digits))))
digits = digits
))
)
)
}
}
@@ -927,9 +1019,11 @@ get_skimmers.rsi <- function(column) {
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$rsi"), envir = frms[[ind]]),
error = function(e) NULL)
error = function(e) NULL
)
tryCatch(ab_name(as.character(calls[[length(calls)]][[2]]), language = NULL),
error = function(e) NA_character_)
error = function(e) NA_character_
)
} else {
NA_character_
}
@@ -941,9 +1035,9 @@ get_skimmers.rsi <- function(column) {
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)
prop_R = ~ proportion_R(., minimum = 0),
prop_S = ~ susceptibility(., minimum = 0),
prop_I = ~ proportion_I(., minimum = 0)
)
}
+39 -20
View File
@@ -44,7 +44,9 @@ rsi_calc <- function(...,
data_vars <- dots2vars(...)
dots_df <- switch(1, ...)
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)
@@ -55,7 +57,9 @@ rsi_calc <- function(...,
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)
"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)) {
@@ -75,8 +79,10 @@ rsi_calc <- function(...,
} 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 <- 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]
@@ -89,7 +95,7 @@ rsi_calc <- function(...,
x <- NULL
try(x <- as.data.frame(dots, stringsAsFactors = FALSE), silent = TRUE)
if (is.null(x)) {
# support for example_isolates %pm>% group_by(hospital_id) %pm>% summarise(amox = susceptibility(GEN, AMX))
# support for example_isolates %pm>% group_by(ward) %pm>% summarise(amox = susceptibility(GEN, AMX))
x <- as.data.frame(list(...), stringsAsFactors = FALSE)
}
}
@@ -125,9 +131,11 @@ rsi_calc <- function(...,
x_transposed <- as.list(as.data.frame(t(x), stringsAsFactors = FALSE))
if (only_all_tested == TRUE) {
# no NAs in any column
y <- apply(X = as.data.frame(lapply(x, as.integer), stringsAsFactors = FALSE),
y <- apply(
X = as.data.frame(lapply(x, as.integer), stringsAsFactors = FALSE),
MARGIN = 1,
FUN = min)
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) !(any(is.na(y)))))
} else {
@@ -151,7 +159,8 @@ rsi_calc <- function(...,
warning_("Increase speed by transforming to class <rsi> on beforehand:\n",
" your_data %>% mutate_if(is.rsi.eligible, as.rsi)\n",
" your_data %>% mutate(across(where(is.rsi.eligible), as.rsi))",
call = FALSE)
call = FALSE
)
}
}
@@ -185,7 +194,9 @@ rsi_calc <- function(...,
ifelse(denominator == 0, "no", paste("only", denominator)),
" results available",
data_vars,
" (`minimum` = ", minimum, ").", call = FALSE)
" (`minimum` = ", minimum, ").",
call = FALSE
)
fraction <- NA_real_
} else {
fraction <- numerator / denominator
@@ -226,6 +237,7 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
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
@@ -251,11 +263,13 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
}
sum_it <- function(.data) {
out <- data.frame(antibiotic = character(0),
out <- data.frame(
antibiotic = character(0),
interpretation = character(0),
value = double(0),
isolates = integer(0),
stringsAsFactors = FALSE)
stringsAsFactors = FALSE
)
if (data_has_groups) {
group_values <- unique(.data[, which(colnames(.data) %in% groups), drop = FALSE])
rownames(group_values) <- NULL
@@ -279,18 +293,22 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
} else {
col_results$value <- rep(NA_real_, NROW(col_results))
}
out_new <- data.frame(antibiotic = ifelse(isFALSE(translate_ab),
out_new <- data.frame(
antibiotic = ifelse(isFALSE(translate_ab),
colnames(.data)[i],
ab_property(colnames(.data)[i], property = translate_ab, language = language)),
ab_property(colnames(.data)[i], property = translate_ab, language = language)
),
interpretation = col_results$interpretation,
value = col_results$value,
isolates = col_results$isolates,
stringsAsFactors = FALSE)
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))
each = nrow(out_new) / nrow(group_values)
)
group_values <- group_values[repeated, , drop = FALSE]
}
out_new <- cbind(group_values, out_new)
@@ -331,9 +349,9 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
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)]), ])
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), ]
out <- out[order(out$antibiotic, out$interpretation), , drop = FALSE]
}
if (type == "proportion") {
@@ -344,8 +362,8 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
}
rownames(out) <- NULL
class(out) <- c("rsi_df", class(out))
out
out <- as_original_data_class(out, class(data.bak))
structure(out, class = c("rsi_df", class(out)))
}
get_translate_ab <- function(translate_ab) {
@@ -359,7 +377,8 @@ get_translate_ab <- function(translate_ab) {
stop_ifnot(translate_ab %in% colnames(AMR::antibiotics),
"invalid value for 'translate_ab', this must be a column name of the antibiotics data set\n",
"or TRUE (equals 'name') or FALSE to not translate at all.",
call = FALSE)
call = FALSE
)
translate_ab
}
}
+4 -3
View File
@@ -32,7 +32,8 @@ rsi_df <- function(data,
as_percent = FALSE,
combine_SI = TRUE,
combine_IR = FALSE) {
rsi_calc_df(type = "both",
rsi_calc_df(
type = "both",
data = data,
translate_ab = translate_ab,
language = language,
@@ -40,6 +41,6 @@ rsi_df <- function(data,
as_percent = as_percent,
combine_SI = combine_SI,
combine_IR = combine_IR,
combine_SI_missing = missing(combine_SI))
combine_SI_missing = missing(combine_SI)
)
}
+3 -3
View File
@@ -28,13 +28,13 @@
#' @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.
#' @inheritSection lifecycle Stable Lifecycle
#' @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
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' skewness(runif(1000))
skewness <- function(x, na.rm = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
UseMethod("skewness")
@@ -50,7 +50,7 @@ skewness.default <- function(x, na.rm = FALSE) {
x <- x[!is.na(x)]
}
n <- length(x)
(sum((x - mean(x))^3) / n) / (sum((x - mean(x)) ^ 2) / n) ^ (3 / 2)
(sum((x - mean(x))^3) / n) / (sum((x - mean(x))^2) / n)^(3 / 2)
}
#' @method skewness matrix
BIN
View File
Binary file not shown.
+116 -102
View File
@@ -23,133 +23,143 @@
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Translate Strings from AMR Package
#' Translate Strings from the AMR Package
#'
#' For language-dependent output of AMR functions, like [mo_name()], [mo_gramstain()], [mo_type()] and [ab_name()].
#' @inheritSection lifecycle Stable Lifecycle
#' @details Strings will be translated to foreign languages if they are defined in a local translation file. Additions to this file can be suggested at our repository. The file can be found here: <https://github.com/msberends/AMR/blob/main/data-raw/translations.tsv>. This file will be read by all functions where a translated output can be desired, like all [`mo_*`][mo_property()] functions (such as [mo_name()], [mo_gramstain()], [mo_type()], etc.) and [`ab_*`][ab_property()] functions (such as [ab_name()], [ab_group()], etc.).
#' @param x text to translate
#' @param language language to choose. Use one of these supported language names or ISO-639-1 codes: `r paste0('"', sapply(LANGUAGES_SUPPORTED_NAMES, function(x) x[[1]]), '" ("' , LANGUAGES_SUPPORTED, '")', collapse = ", ")`.
#' @details The currently `r length(LANGUAGES_SUPPORTED)` supported languages are `r vector_and(sapply(LANGUAGES_SUPPORTED_NAMES, function(x) x[[1]]), quotes = FALSE, sort = FALSE)`. All these languages have translations available for all antimicrobial agents and colloquial microorganism names.
#'
#' Currently supported languages are: `r vector_and(names(LANGUAGES_SUPPORTED), quotes = FALSE)`. All these languages have translations available for all antimicrobial agents and colloquial microorganism names.
#'
#' Please suggest your own translations [by creating a new issue on our repository](https://github.com/msberends/AMR/issues/new?title=Translations).
#' 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()]), if that language is supported. But the language to be used can be overwritten in two ways and will be checked in this order:
#' 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 R option `AMR_locale`, e.g. by running `options(AMR_locale = "de")`
#' 2. Setting the system variable `LANGUAGE` or `LANG`, e.g. by adding `LANGUAGE="de_DE.utf8"` to your `.Renviron` file in your home directory
#' 1. Setting the R option `AMR_locale`, either by using `set_AMR_locale()` or by running e.g. `options(AMR_locale = "de")`.
#'
#' 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.
#' 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 R option `AMR_locale` is set, the system variables `LANGUAGE` and `LANG` will be ignored.
#' @inheritSection AMR Read more on Our Website!
#' @rdname translate
#' @name translate
#' @export
#' @examples
#' # The 'language' argument of below functions
#' # will be set automatically to your system language
#' # with get_AMR_locale()
#' # Current settings (based on system language)
#' ab_name("Ciprofloxacin")
#' mo_name("Coagulase-negative Staphylococcus")
#'
#' # English
#' mo_name("CoNS", language = "en")
#' #> "Coagulase-negative Staphylococcus (CoNS)"
#' # setting another language
#' set_AMR_locale("Greek")
#' ab_name("Ciprofloxacin")
#' mo_name("Coagulase-negative Staphylococcus")
#'
#' # Danish
#' mo_name("CoNS", language = "da")
#' #> "Koagulase-negative stafylokokker (KNS)"
#' set_AMR_locale("Spanish")
#' ab_name("Ciprofloxacin")
#' mo_name("Coagulase-negative Staphylococcus")
#'
#' # Dutch
#' mo_name("CoNS", language = "nl")
#' #> "Coagulase-negatieve Staphylococcus (CNS)"
#' # set_AMR_locale() understands endonyms, English exonyms, and ISO-639-1:
#' set_AMR_locale("Deutsch")
#' set_AMR_locale("German")
#' set_AMR_locale("de")
#'
#' # German
#' mo_name("CoNS", language = "de")
#' #> "Koagulase-negative Staphylococcus (KNS)"
#'
#' # Italian
#' mo_name("CoNS", language = "it")
#' #> "Staphylococcus negativo coagulasi (CoNS)"
#'
#' # Portuguese
#' mo_name("CoNS", language = "pt")
#' #> "Staphylococcus coagulase negativo (CoNS)"
#'
#' # Spanish
#' mo_name("CoNS", language = "es")
#' #> "Staphylococcus coagulasa negativo (SCN)"
#' # reset to system default
#' reset_AMR_locale()
get_AMR_locale <- function() {
# AMR versions 1.3.0 and prior used the environmental variable:
if (!identical("", Sys.getenv("AMR_locale"))) {
options(AMR_locale = Sys.getenv("AMR_locale"))
if (!is.null(getOption("AMR_locale", default = NULL))) {
return(validate_language(getOption("AMR_locale"), extra_txt = "set with `options(AMR_locale = ...)`"))
}
if (!is.null(getOption("AMR_locale", default = NULL))) {
lang <- getOption("AMR_locale")
if (lang %in% LANGUAGES_SUPPORTED) {
return(lang)
} else {
stop_("unsupported language set as option 'AMR_locale': \"", lang, "\" - use either ",
vector_or(paste0('"', LANGUAGES_SUPPORTED, '" (', names(LANGUAGES_SUPPORTED), ")"), quotes = FALSE))
}
} else {
lang <- ""
# now check the LANGUAGE system variable - return it if set
if (!identical("", Sys.getenv("LANGUAGE"))) {
return(coerce_language_setting(Sys.getenv("LANGUAGE")))
lang <- Sys.getenv("LANGUAGE")
}
if (!identical("", Sys.getenv("LANG"))) {
return(coerce_language_setting(Sys.getenv("LANG")))
lang <- Sys.getenv("LANG")
}
if (lang == "") {
lang <- Sys.getlocale("LC_COLLATE")
}
# fallback - automatic determination based on LC_COLLATE
if (interactive() && message_not_thrown_before("get_AMR_locale", entire_session = TRUE)) {
lang <- coerce_language_setting(Sys.getlocale("LC_COLLATE"))
if (lang != "en") {
message_("Assuming the ", names(LANGUAGES_SUPPORTED)[LANGUAGES_SUPPORTED == lang],
" language for the AMR package. Change this with `options(AMR_locale = \"...\")` or see `?get_AMR_locale()`. ",
"Supported languages are ", vector_and(names(LANGUAGES_SUPPORTED), quotes = FALSE),
". This note will be shown once per session.")
lang <- find_language(lang)
if (lang != "en" && interactive() && message_not_thrown_before("get_AMR_locale", entire_session = TRUE)) {
message_(
"Assuming the ", LANGUAGES_SUPPORTED_NAMES[[lang]]$exonym, " language (",
LANGUAGES_SUPPORTED_NAMES[[lang]]$endonym, ") for the AMR package. Change this with `set_AMR_locale()`. ",
"This note will be shown once per session."
)
}
return(lang)
}
coerce_language_setting(Sys.getlocale("LC_COLLATE"))
lang
}
coerce_language_setting <- function(lang) {
# grepl() with ignore.case = FALSE is 8x faster than %like_case%
if (grepl("^(English|en_|EN_)", lang, ignore.case = FALSE, perl = TRUE)) {
# as first option to optimise speed
"en"
} else if (grepl("^(German|Deutsch|de_|DE_)", lang, ignore.case = FALSE, perl = TRUE)) {
"de"
} else if (grepl("^(Dutch|Nederlands|nl_|NL_)", lang, ignore.case = FALSE, perl = TRUE)) {
"nl"
} else if (grepl("^(Danish|Dansk|da_|DA_)", lang, ignore.case = FALSE, perl = TRUE)) {
"da"
} else if (grepl("^(Spanish|Espa.+ol|es_|ES_)", lang, ignore.case = FALSE, perl = TRUE)) {
"es"
} else if (grepl("^(Italian|Italiano|it_|IT_)", lang, ignore.case = FALSE, perl = TRUE)) {
"it"
} else if (grepl("^(French|Fran.+ais|fr_|FR_)", lang, ignore.case = FALSE, perl = TRUE)) {
"fr"
} else if (grepl("^(Portuguese|Portugu.+s|pt_|PT_)", lang, ignore.case = FALSE, perl = TRUE)) {
"pt"
} else if (grepl("^(Russian|pycc|ru_|RU_)", lang, ignore.case = FALSE, perl = TRUE)) {
"ru"
} else if (grepl("^(Swedish|Svenskt|sv_|SV_)", lang, ignore.case = FALSE, perl = TRUE)) {
"sv"
} else {
# other language -> set to English
"en"
#' @rdname translate
#' @export
set_AMR_locale <- function(language) {
language <- validate_language(language)
options(AMR_locale = language)
message_("Using the ", LANGUAGES_SUPPORTED_NAMES[[language]]$exonym, " language (", LANGUAGES_SUPPORTED_NAMES[[language]]$endonym, ") for the AMR package for this session.")
}
#' @rdname translate
#' @export
reset_AMR_locale <- function() {
options(AMR_locale = NULL)
}
#' @rdname translate
#' @export
translate_AMR <- function(x, language = get_AMR_locale()) {
translate_into_language(x, language = language)
}
validate_language <- function(language, extra_txt = character(0)) {
if (trimws(tolower(language)) %in% c("en", "english", "", "false", NA)) {
return("en")
}
lang <- find_language(language, 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(function(l, n, check = language) {
grepl(paste0(
"^(", l[1], "|", l[2], "|",
n, "(_|$)|", toupper(n), "(_|$))"
),
check,
ignore.case = FALSE,
perl = TRUE,
useBytes = FALSE
)
},
LANGUAGES_SUPPORTED_NAMES,
LANGUAGES_SUPPORTED,
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_AMR <- function(from,
translate_into_language <- function(from,
language = get_AMR_locale(),
only_unknown = FALSE,
only_affect_ab_names = FALSE,
only_affect_mo_names = FALSE) {
if (is.null(language)) {
return(from)
}
@@ -162,15 +172,12 @@ translate_AMR <- function(from,
from_unique <- unique(from)
from_unique_translated <- from_unique
stop_ifnot(language %in% LANGUAGES_SUPPORTED,
"unsupported language: \"", language, "\" - use either ",
vector_or(LANGUAGES_SUPPORTED, quotes = TRUE),
call = FALSE)
# get ISO-639-1 of language
lang <- validate_language(language)
# only keep lines where translation is available for this language
df_trans <- df_trans[which(!is.na(df_trans[, language, drop = TRUE])), , drop = FALSE]
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[, language, drop = TRUE]), , drop = FALSE]
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")
}
@@ -195,19 +202,26 @@ translate_AMR <- function(from,
error = function(e) {
warning_("Translation not possible. Please open an issue on GitHub (https://github.com/msberends/AMR/issues).")
return(FALSE)
})
}
)
if (NROW(df_trans) == 0 | !any_form_in_patterns) {
return(from)
}
lapply(seq_len(nrow(df_trans)),
function(i) from_unique_translated <<- gsub(pattern = df_trans$pattern[i],
replacement = df_trans[i, language, drop = TRUE],
lapply(
seq_len(nrow(df_trans)),
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]))
perl = df_trans$regular_expr[i]
)
}
)
# force UTF-8 for diacritics
from_unique_translated <- enc2utf8(from_unique_translated)
+13 -1
View File
@@ -28,8 +28,9 @@
# They are to convert AMR-specific classes to bare characters and integers.
# All of them will be exported using s3_register() in R/zzz.R when loading the package.
# S3: ab_selector
# see https://github.com/tidyverse/dplyr/issues/5955 why this is required
# S3: ab_selector
vec_ptype2.character.ab_selector <- function(x, y, ...) {
x
}
@@ -40,6 +41,17 @@ 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
+1 -1
View File
@@ -35,7 +35,7 @@
#' 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/.>
#' @inheritSection AMR Read more on Our Website!
#' @name WHOCC
#' @rdname WHOCC
#' @examples
+26 -13
View File
@@ -26,16 +26,19 @@
# set up package environment, used by numerous AMR functions
pkg_env <- new.env(hash = FALSE)
pkg_env$mo_failed <- character(0)
pkg_env$mo_field_abbreviations <- c("AIEC", "ATEC", "BORSA", "CRSM", "DAEC", "EAEC",
pkg_env$mo_field_abbreviations <- c(
"AIEC", "ATEC", "BORSA", "CRSM", "DAEC", "EAEC",
"EHEC", "EIEC", "EPEC", "ETEC", "GISA", "MRPA",
"MRSA", "MRSE", "MSSA", "MSSE", "NMEC", "PISP",
"PRSP", "STEC", "UPEC", "VISA", "VISP", "VRE",
"VRSA", "VRSP")
"VRSA", "VRSP"
)
# determine info icon for messages
utf8_supported <- isTRUE(base::l10n_info()$`UTF-8`)
is_latex <- tryCatch(import_fn("is_latex_output", "knitr", error_on_fail = FALSE)(),
error = function(e) FALSE)
error = function(e) FALSE
)
if (utf8_supported && !is_latex) {
# \u2139 is a symbol officially named 'information source'
pkg_env$info_icon <- "\u2139"
@@ -87,30 +90,35 @@ if (utf8_supported && !is_latex) {
s3_register("vctrs::vec_ptype2", "ab_selector.character")
s3_register("vctrs::vec_ptype2", "character.ab_selector")
s3_register("vctrs::vec_cast", "character.ab_selector")
s3_register("vctrs::vec_ptype2", "ab_selector_any_all.logical")
s3_register("vctrs::vec_ptype2", "logical.ab_selector_any_all")
s3_register("vctrs::vec_cast", "logical.ab_selector_any_all")
s3_register("vctrs::vec_ptype2", "disk.integer")
s3_register("vctrs::vec_ptype2", "integer.disk")
s3_register("vctrs::vec_cast", "integer.disk")
# if mo source exists, fire it up (see mo_source())
try({
try(
{
if (file.exists(getOption("AMR_mo_source", "~/mo_source.rds"))) {
invisible(get_mo_source())
}
}, silent = TRUE)
},
silent = TRUE
)
# be sure to print tibbles as tibbles
if (pkg_is_available("tibble", also_load = FALSE)) {
loadNamespace("tibble")
}
# reference data - they have additional columns compared to `antibiotics` and `microorganisms` to improve speed
# they cannott be part of R/sysdata.rda since CRAN thinks it would make the package too large (+3 MB)
# they cannot be part of R/sysdata.rda since CRAN thinks it would make the package too large (+3 MB)
assign(x = "AB_lookup", value = create_AB_lookup(), envir = asNamespace("AMR"))
assign(x = "MO_lookup", value = create_MO_lookup(), envir = asNamespace("AMR"))
assign(x = "MO.old_lookup", value = create_MO.old_lookup(), envir = asNamespace("AMR"))
# for mo_is_intrinsic_resistant() - saves a lot of time when executed on this vector
assign(x = "INTRINSIC_R", value = create_intr_resistance(), envir = asNamespace("AMR"))
# for building the website, only print first 5 rows of a data set
# if (Sys.getenv("IN_PKGDOWN") != "" && !interactive()) {
# ...
# }
}
# Helper functions --------------------------------------------------------
@@ -131,13 +139,18 @@ create_MO_lookup <- function() {
MO_lookup[which(is.na(MO_lookup$kingdom_index)), "kingdom_index"] <- 5
# use this paste instead of `fullname` to work with Viridans Group Streptococci, etc.
if (length(MO_FULLNAME_LOWER) == nrow(MO_lookup)) {
MO_lookup$fullname_lower <- MO_FULLNAME_LOWER
} else {
MO_lookup$fullname_lower <- ""
warning("MO table updated - Run: source(\"data-raw/_pre_commit_hook.R\")", call. = FALSE)
}
# add a column with only "e coli" like combinations
MO_lookup$g_species <- gsub("^([a-z])[a-z]+ ([a-z]+) ?.*", "\\1 \\2", MO_lookup$fullname_lower, perl = TRUE)
# so arrange data on prevalence first, then kingdom, then full name
MO_lookup[order(MO_lookup$prevalence, MO_lookup$kingdom_index, MO_lookup$fullname_lower), ]
MO_lookup[order(MO_lookup$prevalence, MO_lookup$kingdom_index, MO_lookup$fullname_lower), , drop = FALSE]
}
create_MO.old_lookup <- function() {
@@ -148,7 +161,7 @@ create_MO.old_lookup <- function() {
MO.old_lookup$g_species <- trimws(gsub("^([a-z])[a-z]+ ([a-z]+) ?.*", "\\1 \\2", MO.old_lookup$fullname_lower))
# so arrange data on prevalence first, then full name
MO.old_lookup[order(MO.old_lookup$prevalence, MO.old_lookup$fullname_lower), ]
MO.old_lookup[order(MO.old_lookup$prevalence, MO.old_lookup$fullname_lower), , drop = FALSE]
}
create_intr_resistance <- function() {
+1 -3
View File
@@ -8,9 +8,7 @@
<img src="https://msberends.github.io/AMR/AMR_intro.svg" align="center" height="300px" />
The latest built **source package** (`AMR_latest.tar.gz`) can be found in folder [/data-raw/](https://github.com/msberends/AMR/tree/main/data-raw).
`AMR` is a free, open-source and independent R package 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 antimicrobial resistance data analysis, that can therefore empower epidemiological analyses to continuously enable surveillance and treatment evaluation in any setting. It is currently being used in over 150 countries.
`AMR` is a free, open-source and independent R package 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 antimicrobial resistance data analysis, that can therefore empower epidemiological analyses to continuously enable surveillance and treatment evaluation in any setting. It is currently being used in over 175 countries.
After installing this package, R knows ~71,000 distinct microbial species and all ~570 antibiotic, antimycotic, and antiviral drugs by name and code (including ATC, WHONET/EARS-Net, PubChem, LOINC and SNOMED CT), and knows all about valid R/SI and MIC values. It supports any data format, including WHONET/EARS-Net data. Antimicrobial names and group names are available in Danish, Dutch, English, French, German, Italian, Portuguese and Spanish.
+32 -19
View File
@@ -26,14 +26,40 @@
title: "AMR (for R)"
url: "https://msberends.github.io/AMR/"
development:
mode: "release" # improves indexing by search engines
version_tooltip: "Latest development version"
template:
bootstrap: 5
bootswatch: "flatly"
assets: "pkgdown/logos" # use logos in this folder
bslib:
code_font: {google: "Fira Code"}
# body-text-align: "justify"
line-height-base: 1.75
# the green "success" colour of this bootstrap theme should be the same as the green in our logo
success: "#128f76"
link-color: "#128f76"
navbar-padding-y: "0.5rem"
opengraph:
twitter:
creator: "@msberends"
site: "@univgroningen"
card: summary_large_image
news:
one_page: true
cran_dates: true
footer:
structure:
left: [devtext]
right: [logo]
components:
devtext: '<code>AMR</code> (for R). Developed at the <a target="_blank" href="https://www.rug.nl">University of Groningen</a> in collaboration with non-profit organisations<br><a target="_blank" href="https://www.certe.nl">Certe Medical Diagnostics and Advice Foundation</a> and <a target="_blank" href="https://www.umcg.nl">University Medical Center Groningen</a>.'
logo: '<a target="_blank" href="https://www.rug.nl"><img src="https://github.com/msberends/AMR/raw/main/pkgdown/logos/logo_rug.svg" style="max-width: 200px;"></a>'
home:
sidebar:
structure: [toc, links, authors, citation]
navbar:
title: "AMR (for R)"
left:
@@ -73,9 +99,9 @@ navbar:
- text: "Get properties of an antibiotic"
icon: "fa-capsules"
href: "reference/ab_property.html" # reference instead of an article
- text: "Other: benchmarks"
icon: "fa-shipping-fast"
href: "articles/benchmarks.html"
# - text: "Other: benchmarks"
# icon: "fa-shipping-fast"
# href: "articles/benchmarks.html"
- text: "Manual"
icon: "fa-book-open"
href: "reference/index.html"
@@ -161,7 +187,6 @@ reference:
- "`catalogue_of_life`"
- "`catalogue_of_life_version`"
- "`WHOCC`"
- "`lifecycle`"
- "`example_isolates_unclean`"
- "`rsi_translation`"
- "`WHONET`"
@@ -199,15 +224,3 @@ reference:
in a future version.
contents:
- "`AMR-deprecated`"
template:
bootstrap: 3
opengraph:
twitter:
creator: "@msberends"
site: "@univgroningen"
card: summary_large_image
assets: "pkgdown/logos" # use logos in this folder
params:
noindex: false
bootswatch: "flatly"
Binary file not shown.
+1 -1
View File
@@ -71673,7 +71673,7 @@
"7553-1","Origanum vulgare Ab.IgG","ACnc","Pt","Ser","Qn","","ALLERGY","2.27","MIN","","ACTIVE","","1","","","","","","Y","","ABS; Aby; Allergen; Allergens; ALLERGY TESTING; Antby; Anti; Antibodies; Antibody; Arbitrary concentration; Autoantibodies; Autoantibody; f283; Immune globulin G; Immunoglobulin G; Oregano; Oreganum; Point in time; QNT; Quan; Quant; Quantitative; Random; Rf283; Serum; SR","Oregano IgG Qn","Both","","","","","Oregano IgG Ab [Units/volume] in Serum","","","","","","","0","0","0","","","","","","1.0h(2)","","Oregano IgG Qn (S)"
"75531-4","Enrollment basis","Type","Pt","^Patient","Nom","","SURVEY.PCORNET","2.50","MIN","","ACTIVE","","4","","","","","","","","Nominal; Point in time; Random; Survey; SURVEY.PCORNET; Typ","Enrollment basis","Observation","","","","","Enrollment basis","","","","","","","0","0","0","","","","","","2.50","",""
"75532-2","Applicable accrediting agency for unit","Type","Pt","{Nursing unit}","Nom","NMMDS","SURVEY.NMMDS","2.50","MIN","Types of accreditation that are appropriate or applicable to a unit or service. The unit may or may not have received the accreditation.","ACTIVE","","4","","","","","","","","Nominal; Nursing Management Minimum Data Set; Point in time; Random; Survey; SURVEY.NMMDS; Typ","","Observation","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","Applicable accrediting agency for unit [NMMDS]","","","","","","","0","0","0","","NMMDS","","","","2.50","",""
"75533-0","Accreditation, certification, & licensure panel","-","Pt","{Nursing unit}","-","NMMDS","PANEL.SURVEY.NMMDS","2.52","MIN","The set of terms in this panel are used to indicate quality assurance organizations of the nursing delivery unit/service by 3 different quality measure categories: accreditation, certification and licensure. Accreditation is a seal of approval given by private, nationally recognized groups that check on the quality of care at health care facilities and organizations. Health care organizations must meet certain quality standards in order to be accredited. Certification is the formal recognition of the knowledge, skills, and experience demonstrated by the achievement of standards that are identified by the profession² (ANA, 2009). Licensure is the granting of authority to practice² (ANA, 2009). State agencies determine the requirements for licensure and examine the competency necessary to meet quality standards.","ACTIVE","","4","","","","","","","","Nursing Management Minimum Data Set; Pan; PANEL.SURVEY.NMMDS; Panl; Pnl; Point in time; Random; Survey; SURVEY.NMMDS","","","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","NMMDS accreditation, certification, and licensure panel [NMMDS]","","","","","","","0","0","0","","NMMDS","Panel","","","2.50","",""
"75533-0","Accreditation, certification, & licensure panel","-","Pt","{Nursing unit}","-","NMMDS","PANEL.SURVEY.NMMDS","2.52","MIN","The set of terms in this panel are used to indicate quality assurance organizations of the nursing delivery unit/service by 3 different quality measure categories: accreditation, certification and licensure. Accreditation is a seal of approval given by private, nationally recognized groups that check on the quality of care at health care facilities and organizations. Health care organizations must meet certain quality standards in order to be accredited. Certification is the formal recognition of the knowledge, skills, and experience demonstrated by the achievement of standards that are identified by the profession² (ANA, 2009). Licensure is the granting of authority to practise² (ANA, 2009). State agencies determine the requirements for licensure and examine the competency necessary to meet quality standards.","ACTIVE","","4","","","","","","","","Nursing Management Minimum Data Set; Pan; PANEL.SURVEY.NMMDS; Panl; Pnl; Point in time; Random; Survey; SURVEY.NMMDS","","","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","NMMDS accreditation, certification, and licensure panel [NMMDS]","","","","","","","0","0","0","","NMMDS","Panel","","","2.50","",""
"75534-8","Accreditation received","Type","Pt","{Nursing unit}","Nom","NMMDS","SURVEY.NMMDS","2.50","MIN","Types of accreditation obtained by a unit to demonstrate quality of care. Accreditation is a seal of approval given by private, nationally recognized groups that check on the quality of care at health care facilities and organizations. Health care organizations must meet certain quality standards in order to be accredited.","ACTIVE","","4","","","","","","","","Nominal; Nursing Management Minimum Data Set; Point in time; Random; Survey; SURVEY.NMMDS; Typ","","Observation","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","Accreditation received [NMMDS]","","","","","","","0","0","0","","NMMDS","","","","2.50","",""
"75535-5","Certification received","Type","Pt","{Nursing unit}","Nom","NMMDS","SURVEY.NMMDS","2.50","MIN","Types of certification obtained by a unit to demonstrate quality care.","ACTIVE","","4","","","","","","","","Nominal; Nursing Management Minimum Data Set; Point in time; Random; Survey; SURVEY.NMMDS; Typ","","Observation","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","Certification received [NMMDS]","","","","","","","0","0","0","","NMMDS","","","","2.50","",""
"75536-3","Applicable certification agency for unit","Type","Pt","{Nursing unit}","Nom","NMMDS","SURVEY.NMMDS","2.50","MIN","Types of certification that are appropriate or applicable to a unit or service. The unit may or may not have received the certification.","ACTIVE","","4","","","","","","","","Nominal; Nursing Management Minimum Data Set; Point in time; Random; Survey; SURVEY.NMMDS; Typ","","Observation","","","Copyright © 2006 Diane Huber and Connie Delaney. Used with permission.","","Applicable certification agency for unit [NMMDS]","","","","","","","0","0","0","","NMMDS","","","","2.50","",""
Can't render this file because it is too large.
+18 -9
View File
@@ -25,12 +25,16 @@
# some old R instances have trouble installing tinytest, so we ship it too
install.packages("data-raw/tinytest_1.3.1.tar.gz", dependencies = c("Depends", "Imports", "LinkingTo"))
install.packages("data-raw/AMR_latest.tar.gz", dependencies = FALSE)
install.packages(getwd(), repos = NULL, type = "source")
pkg_suggests <- gsub("[^a-zA-Z0-9]+", "",
pkg_suggests <- gsub(
"[^a-zA-Z0-9]+", "",
unlist(strsplit(unlist(packageDescription("AMR",
fields = c("Suggests", "Enhances", "LinkingTo"))),
split = ", ?")))
fields = c("Suggests", "Enhances", "LinkingTo")
)),
split = ", ?"
))
)
pkg_suggests <- unname(pkg_suggests[!is.na(pkg_suggests)])
cat("################################################\n")
cat("Packages listed in Suggests/Enhances:", paste(pkg_suggests, collapse = ", "), "\n")
@@ -51,19 +55,23 @@ for (i in seq_len(length(to_install))) {
type = "source",
repos = "https://cran.rstudio.com/",
dependencies = c("Depends", "Imports", "LinkingTo"),
quiet = FALSE),
quiet = FALSE
),
# message = function(m) invisible(),
warning = function(w) message(w$message),
error = function(e) message(e$message))
error = function(e) message(e$message)
)
if (.Platform$OS.type != "unix" && !to_install[i] %in% rownames(utils::installed.packages())) {
tryCatch(install.packages(to_install[i],
type = "binary",
repos = "https://cran.rstudio.com/",
dependencies = c("Depends", "Imports", "LinkingTo"),
quiet = FALSE),
quiet = FALSE
),
# message = function(m) invisible(),
warning = function(w) message(w$message),
error = function(e) message(e$message))
error = function(e) message(e$message)
)
}
}
@@ -77,6 +85,7 @@ for (i in seq_len(length(to_update))) {
tryCatch(update.packages(to_update[i], repos = "https://cran.rstudio.com/", ask = FALSE),
# message = function(m) invisible(),
warning = function(w) message(w$message),
error = function(e) message(e$message))
error = function(e) message(e$message)
)
cat("Updated to '", to_update[i], "' v", as.character(packageVersion(to_update[i])), "\n", sep = "")
}
-343
View File
@@ -1,343 +0,0 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# Run this file to update the package using:
# source("data-raw/_internals.R")
library(dplyr, warn.conflicts = FALSE)
devtools::load_all(quiet = TRUE)
old_globalenv <- ls(envir = globalenv())
# Save internal data to R/sysdata.rda -------------------------------------
# See 'data-raw/eucast_rules.tsv' for the EUCAST reference file
EUCAST_RULES_DF <- utils::read.delim(file = "data-raw/eucast_rules.tsv",
skip = 10,
sep = "\t",
stringsAsFactors = FALSE,
header = TRUE,
strip.white = TRUE,
na = c(NA, "", NULL)) %>%
# take the order of the reference.rule_group column in the original data file
mutate(reference.rule_group = factor(reference.rule_group,
levels = unique(reference.rule_group),
ordered = TRUE),
sorting_rule = ifelse(grepl("^Table", reference.rule, ignore.case = TRUE), 1, 2)) %>%
arrange(reference.rule_group,
reference.version,
sorting_rule,
reference.rule) %>%
mutate(reference.rule_group = as.character(reference.rule_group)) %>%
select(-sorting_rule)
# Translations
TRANSLATIONS <- utils::read.delim(file = "data-raw/translations.tsv",
sep = "\t",
stringsAsFactors = FALSE,
header = TRUE,
blank.lines.skip = TRUE,
fill = TRUE,
strip.white = TRUE,
encoding = "UTF-8",
fileEncoding = "UTF-8",
na.strings = c(NA, "", NULL),
allowEscapes = TRUE, # else "\\1" will be imported as "\\\\1"
quote = "")
# for checking input in `language` argument in e.g. mo_*() and ab_*() functions
LANGUAGES_SUPPORTED <- c(Danish = "da",
German = "de",
English = "en",
Spanish = "es",
French = "fr",
Italian = "it",
Dutch = "nl",
Portuguese = "pt",
Russian = "ru",
Swedish = "sv")
# EXAMPLE_ISOLATES <- readRDS("data-raw/example_isolates.rds")
# vectors of CoNS and CoPS, improves speed in as.mo()
create_species_cons_cops <- function(type = c("CoNS", "CoPS")) {
# Determination of which staphylococcal species are CoNS/CoPS according to:
# - Becker et al. 2014, PMID 25278577
# - Becker et al. 2019, PMID 30872103
# - Becker et al. 2020, PMID 32056452
# this function returns class <mo>
MO_staph <- AMR::microorganisms
MO_staph <- MO_staph[which(MO_staph$genus == "Staphylococcus"), , drop = FALSE]
if (type == "CoNS") {
MO_staph[which(MO_staph$species %in% c("coagulase-negative", "argensis", "arlettae",
"auricularis", "borealis", "caeli", "capitis", "caprae",
"carnosus", "casei", "chromogenes", "cohnii", "condimenti",
"croceilyticus",
"debuckii", "devriesei", "edaphicus", "epidermidis",
"equorum", "felis", "fleurettii", "gallinarum",
"haemolyticus", "hominis", "jettensis", "kloosii",
"lentus", "lugdunensis", "massiliensis", "microti",
"muscae", "nepalensis", "pasteuri", "petrasii",
"pettenkoferi", "piscifermentans", "pragensis", "pseudoxylosus",
"pulvereri", "rostri", "saccharolyticus", "saprophyticus",
"sciuri", "simulans", "stepanovicii", "succinus",
"ureilyticus",
"vitulinus", "vitulus", "warneri", "xylosus",
"caledonicus", "canis",
"durrellii", "lloydii")
| (MO_staph$species == "schleiferi" & MO_staph$subspecies %in% c("schleiferi", ""))),
"mo", drop = TRUE]
} else if (type == "CoPS") {
MO_staph[which(MO_staph$species %in% c("coagulase-positive", "coagulans",
"agnetis", "argenteus",
"cornubiensis",
"delphini", "lutrae",
"hyicus", "intermedius",
"pseudintermedius", "pseudointermedius",
"schweitzeri", "simiae",
"roterodami")
| (MO_staph$species == "schleiferi" & MO_staph$subspecies == "coagulans")),
"mo", drop = TRUE]
}
}
create_MO_fullname_lower <- function() {
MO_lookup <- AMR::microorganisms
# use this paste instead of `fullname` to work with Viridans Group Streptococci, etc.
MO_lookup$fullname_lower <- tolower(trimws(paste(MO_lookup$genus,
MO_lookup$species,
MO_lookup$subspecies)))
ind <- MO_lookup$genus == "" | grepl("^[(]unknown ", MO_lookup$fullname, perl = TRUE)
MO_lookup[ind, "fullname_lower"] <- tolower(MO_lookup[ind, "fullname"])
MO_lookup$fullname_lower <- trimws(gsub("[^.a-z0-9/ \\-]+", "", MO_lookup$fullname_lower, perl = TRUE))
MO_lookup$fullname_lower
}
MO_CONS <- create_species_cons_cops("CoNS")
MO_COPS <- create_species_cons_cops("CoPS")
MO_STREP_ABCG <- as.mo(MO_lookup[which(MO_lookup$genus == "Streptococcus"), "mo", drop = TRUE], Lancefield = TRUE) %in% c("B_STRPT_GRPA", "B_STRPT_GRPB", "B_STRPT_GRPC", "B_STRPT_GRPG")
MO_FULLNAME_LOWER <- create_MO_fullname_lower()
# antibiotic groups
# (these will also be used for eucast_rules() and understanding data-raw/eucast_rules.tsv)
globalenv_before_ab <- c(ls(envir = globalenv()), "globalenv_before_ab")
AB_AMINOGLYCOSIDES <- antibiotics %>% filter(group %like% "aminoglycoside") %>% pull(ab)
AB_AMINOPENICILLINS <- as.ab(c("AMP", "AMX"))
AB_ANTIFUNGALS <- AB_lookup %>% filter(group %like% "antifungal") %>% pull(ab)
AB_ANTIMYCOBACTERIALS <- AB_lookup %>% filter(group %like% "antimycobacterial") %>% pull(ab)
AB_CARBAPENEMS <- antibiotics %>% filter(group %like% "carbapenem") %>% pull(ab)
AB_CEPHALOSPORINS <- antibiotics %>% filter(group %like% "cephalosporin") %>% pull(ab)
AB_CEPHALOSPORINS_1ST <- antibiotics %>% filter(group %like% "cephalosporin.*1") %>% pull(ab)
AB_CEPHALOSPORINS_2ND <- antibiotics %>% filter(group %like% "cephalosporin.*2") %>% pull(ab)
AB_CEPHALOSPORINS_3RD <- antibiotics %>% filter(group %like% "cephalosporin.*3") %>% pull(ab)
AB_CEPHALOSPORINS_4TH <- antibiotics %>% filter(group %like% "cephalosporin.*4") %>% pull(ab)
AB_CEPHALOSPORINS_5TH <- antibiotics %>% filter(group %like% "cephalosporin.*5") %>% pull(ab)
AB_CEPHALOSPORINS_EXCEPT_CAZ <- AB_CEPHALOSPORINS[AB_CEPHALOSPORINS != "CAZ"]
AB_FLUOROQUINOLONES <- antibiotics %>% filter(atc_group2 %like% "fluoroquinolone" | (group %like% "quinolone" & is.na(atc_group2))) %>% pull(ab)
AB_GLYCOPEPTIDES <- antibiotics %>% filter(group %like% "glycopeptide") %>% pull(ab)
AB_LIPOGLYCOPEPTIDES <- as.ab(c("DAL", "ORI", "TLV")) # dalba/orita/tela
AB_GLYCOPEPTIDES_EXCEPT_LIPO <- AB_GLYCOPEPTIDES[!AB_GLYCOPEPTIDES %in% AB_LIPOGLYCOPEPTIDES]
AB_LINCOSAMIDES <- antibiotics %>% filter(atc_group2 %like% "lincosamide" | (group %like% "lincosamide" & is.na(atc_group2))) %>% pull(ab)
AB_MACROLIDES <- antibiotics %>% filter(atc_group2 %like% "macrolide" | (group %like% "macrolide" & is.na(atc_group2))) %>% pull(ab)
AB_OXAZOLIDINONES <- antibiotics %>% filter(group %like% "oxazolidinone") %>% pull(ab)
AB_PENICILLINS <- antibiotics %>% filter(group %like% "penicillin") %>% pull(ab)
AB_POLYMYXINS <- antibiotics %>% filter(group %like% "polymyxin") %>% pull(ab)
AB_QUINOLONES <- antibiotics %>% filter(group %like% "quinolone") %>% pull(ab)
AB_STREPTOGRAMINS <- antibiotics %>% filter(atc_group2 %like% "streptogramin") %>% pull(ab)
AB_TETRACYCLINES <- antibiotics %>% filter(group %like% "tetracycline") %>% pull(ab)
AB_TETRACYCLINES_EXCEPT_TGC <- AB_TETRACYCLINES[AB_TETRACYCLINES != "TGC"]
AB_TRIMETHOPRIMS <- antibiotics %>% filter(group %like% "trimethoprim") %>% pull(ab)
AB_UREIDOPENICILLINS <- as.ab(c("PIP", "TZP", "AZL", "MEZ"))
AB_BETALACTAMS <- c(AB_PENICILLINS, AB_CEPHALOSPORINS, AB_CARBAPENEMS)
# this will be used for documentation:
DEFINED_AB_GROUPS <- ls(envir = globalenv())
DEFINED_AB_GROUPS <- DEFINED_AB_GROUPS[!DEFINED_AB_GROUPS %in% globalenv_before_ab]
create_AB_lookup <- function() {
AB_lookup <- AMR::antibiotics
AB_lookup$generalised_name <- generalise_antibiotic_name(AB_lookup$name)
AB_lookup$generalised_synonyms <- lapply(AB_lookup$synonyms, generalise_antibiotic_name)
AB_lookup$generalised_abbreviations <- lapply(AB_lookup$abbreviations, generalise_antibiotic_name)
AB_lookup$generalised_loinc <- lapply(AB_lookup$loinc, generalise_antibiotic_name)
AB_lookup$generalised_all <- unname(lapply(as.list(as.data.frame(t(AB_lookup[,
c("ab", "atc", "cid", "name",
colnames(AB_lookup)[colnames(AB_lookup) %like% "generalised"]),
drop = FALSE]),
stringsAsFactors = FALSE)),
function(x) {
x <- generalise_antibiotic_name(unname(unlist(x)))
x[x != ""]
}))
AB_lookup[, colnames(AB_lookup)[colnames(AB_lookup) %like% "^generalised"]]
}
AB_LOOKUP <- create_AB_lookup()
# Export to package as internal data ----
usethis::use_data(EUCAST_RULES_DF,
TRANSLATIONS,
LANGUAGES_SUPPORTED,
# EXAMPLE_ISOLATES,
MO_CONS,
MO_COPS,
MO_STREP_ABCG,
MO_FULLNAME_LOWER,
AB_LOOKUP,
AB_AMINOGLYCOSIDES,
AB_AMINOPENICILLINS,
AB_ANTIFUNGALS,
AB_ANTIMYCOBACTERIALS,
AB_CARBAPENEMS,
AB_CEPHALOSPORINS,
AB_CEPHALOSPORINS_1ST,
AB_CEPHALOSPORINS_2ND,
AB_CEPHALOSPORINS_3RD,
AB_CEPHALOSPORINS_4TH,
AB_CEPHALOSPORINS_5TH,
AB_CEPHALOSPORINS_EXCEPT_CAZ,
AB_FLUOROQUINOLONES,
AB_LIPOGLYCOPEPTIDES,
AB_GLYCOPEPTIDES,
AB_GLYCOPEPTIDES_EXCEPT_LIPO,
AB_LINCOSAMIDES,
AB_MACROLIDES,
AB_OXAZOLIDINONES,
AB_PENICILLINS,
AB_POLYMYXINS,
AB_QUINOLONES,
AB_STREPTOGRAMINS,
AB_TETRACYCLINES,
AB_TETRACYCLINES_EXCEPT_TGC,
AB_TRIMETHOPRIMS,
AB_UREIDOPENICILLINS,
AB_BETALACTAMS,
DEFINED_AB_GROUPS,
internal = TRUE,
overwrite = TRUE,
version = 2,
compress = "xz")
# Export data sets to the repository in different formats -----------------
write_md5 <- function(object) {
conn <- file(paste0("data-raw/", deparse(substitute(object)), ".md5"))
writeLines(digest::digest(object, "md5"), conn)
close(conn)
}
changed_md5 <- function(object) {
tryCatch({
conn <- file(paste0("data-raw/", deparse(substitute(object)), ".md5"))
compared <- digest::digest(object, "md5") != readLines(con = conn)
close(conn)
compared
}, error = function(e) TRUE)
}
# give official names to ABs and MOs
rsi <- dplyr::mutate(rsi_translation, ab = ab_name(ab), mo = mo_name(mo))
if (changed_md5(rsi)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('rsi_translation')} to {usethis::ui_value('/data-raw/')}"))
write_md5(rsi)
try(saveRDS(rsi, "data-raw/rsi_translation.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(rsi, "data-raw/rsi_translation.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(rsi, "data-raw/rsi_translation.sas"), silent = TRUE)
try(haven::write_sav(rsi, "data-raw/rsi_translation.sav"), silent = TRUE)
try(haven::write_dta(rsi, "data-raw/rsi_translation.dta"), silent = TRUE)
try(openxlsx::write.xlsx(rsi, "data-raw/rsi_translation.xlsx"), silent = TRUE)
}
mo <- dplyr::mutate_if(microorganisms, ~!is.numeric(.), as.character)
if (changed_md5(mo)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('microorganisms')} to {usethis::ui_value('/data-raw/')}"))
write_md5(mo)
try(saveRDS(mo, "data-raw/microorganisms.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(mo, "data-raw/microorganisms.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(dplyr::select(mo, -snomed), "data-raw/microorganisms.sas"), silent = TRUE)
try(haven::write_sav(dplyr::select(mo, -snomed), "data-raw/microorganisms.sav"), silent = TRUE)
try(haven::write_dta(dplyr::select(mo, -snomed), "data-raw/microorganisms.dta"), silent = TRUE)
try(openxlsx::write.xlsx(mo, "data-raw/microorganisms.xlsx"), silent = TRUE)
}
if (changed_md5(microorganisms.old)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('microorganisms.old')} to {usethis::ui_value('/data-raw/')}"))
write_md5(microorganisms.old)
try(saveRDS(microorganisms.old, "data-raw/microorganisms.old.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(microorganisms.old, "data-raw/microorganisms.old.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(microorganisms.old, "data-raw/microorganisms.old.sas"), silent = TRUE)
try(haven::write_sav(microorganisms.old, "data-raw/microorganisms.old.sav"), silent = TRUE)
try(haven::write_dta(microorganisms.old, "data-raw/microorganisms.old.dta"), silent = TRUE)
try(openxlsx::write.xlsx(microorganisms.old, "data-raw/microorganisms.old.xlsx"), silent = TRUE)
}
ab <- dplyr::mutate_if(antibiotics, ~!is.numeric(.), as.character)
if (changed_md5(ab)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('antibiotics')} to {usethis::ui_value('/data-raw/')}"))
write_md5(ab)
try(saveRDS(ab, "data-raw/antibiotics.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(ab, "data-raw/antibiotics.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(ab, "data-raw/antibiotics.sas"), silent = TRUE)
try(haven::write_sav(ab, "data-raw/antibiotics.sav"), silent = TRUE)
try(haven::write_dta(ab, "data-raw/antibiotics.dta"), silent = TRUE)
try(openxlsx::write.xlsx(ab, "data-raw/antibiotics.xlsx"), silent = TRUE)
}
av <- dplyr::mutate_if(antivirals, ~!is.numeric(.), as.character)
if (changed_md5(av)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('antivirals')} to {usethis::ui_value('/data-raw/')}"))
write_md5(av)
try(saveRDS(av, "data-raw/antivirals.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(av, "data-raw/antivirals.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(av, "data-raw/antivirals.sas"), silent = TRUE)
try(haven::write_sav(av, "data-raw/antivirals.sav"), silent = TRUE)
try(haven::write_dta(av, "data-raw/antivirals.dta"), silent = TRUE)
try(openxlsx::write.xlsx(av, "data-raw/antivirals.xlsx"), silent = TRUE)
}
# give official names to ABs and MOs
intrinsicR <- data.frame(microorganism = mo_name(intrinsic_resistant$mo),
antibiotic = ab_name(intrinsic_resistant$ab),
stringsAsFactors = FALSE)
if (changed_md5(intrinsicR)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('intrinsic_resistant')} to {usethis::ui_value('/data-raw/')}"))
write_md5(intrinsicR)
try(saveRDS(intrinsicR, "data-raw/intrinsic_resistant.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(intrinsicR, "data-raw/intrinsic_resistant.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(intrinsicR, "data-raw/intrinsic_resistant.sas"), silent = TRUE)
try(haven::write_sav(intrinsicR, "data-raw/intrinsic_resistant.sav"), silent = TRUE)
try(haven::write_dta(intrinsicR, "data-raw/intrinsic_resistant.dta"), silent = TRUE)
try(openxlsx::write.xlsx(intrinsicR, "data-raw/intrinsic_resistant.xlsx"), silent = TRUE)
}
if (changed_md5(dosage)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('dosage')} to {usethis::ui_value('/data-raw/')}"))
write_md5(dosage)
try(saveRDS(dosage, "data-raw/dosage.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(dosage, "data-raw/dosage.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(dosage, "data-raw/dosage.sas"), silent = TRUE)
try(haven::write_sav(dosage, "data-raw/dosage.sav"), silent = TRUE)
try(haven::write_dta(dosage, "data-raw/dosage.dta"), silent = TRUE)
try(openxlsx::write.xlsx(dosage, "data-raw/dosage.xlsx"), silent = TRUE)
}
# remove leftovers from global env
current_globalenv <- ls(envir = globalenv())
rm(list = current_globalenv[!current_globalenv %in% old_globalenv])
rm(current_globalenv)
+91
View File
@@ -0,0 +1,91 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# Run this file to update the languages used in the packages:
# source("data-raw/_language_update.R")
if (!file.exists("DESCRIPTION") || !"Package: AMR" %in% readLines("DESCRIPTION")) {
stop("Be sure to run this script in the root location of the AMR package folder.\n",
"Working directory expected to contain the DESCRIPTION file of the AMR package.\n",
"Current working directory: ", getwd(),
call. = FALSE
)
}
# save old global env to restore later
lang_env <- new.env(hash = FALSE)
# load current internal data into new env
load("R/sysdata.rda", envir = lang_env)
# replace language objects with updates
message("Reading translation file...")
lang_env$TRANSLATIONS <- utils::read.delim(
file = "data-raw/translations.tsv",
sep = "\t",
stringsAsFactors = FALSE,
header = TRUE,
blank.lines.skip = TRUE,
fill = TRUE,
strip.white = TRUE,
encoding = "UTF-8",
fileEncoding = "UTF-8",
na.strings = c(NA, "", NULL),
allowEscapes = TRUE, # else "\\1" will be imported as "\\\\1"
quote = ""
)
lang_env$LANGUAGES_SUPPORTED_NAMES <- c(
list(en = list(exonym = "English", endonym = "English")),
lapply(
lang_env$TRANSLATIONS[, which(nchar(colnames(lang_env$TRANSLATIONS)) == 2), drop = FALSE],
function(x) list(exonym = x[1], endonym = x[2])
)
)
lang_env$LANGUAGES_SUPPORTED <- names(lang_env$LANGUAGES_SUPPORTED_NAMES)
# save env to internal package data
# usethis::use_data() does not allow to save a list :(
message("Saving to internal data...")
save(
list = names(lang_env),
file = "R/sysdata.rda",
ascii = FALSE,
version = 2,
compress = "xz",
envir = lang_env
)
rm(lang_env)
if ("roxygen2" %in% utils::installed.packages()) {
message("Updating package documentation...")
suppressMessages(roxygen2::roxygenise(package.dir = "."))
} else {
message("NOTE: please install the roxygen2 package to update package documentation, and run this script again.")
}
message("Done!")
+503
View File
@@ -0,0 +1,503 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Data Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2022 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# Run this file to update the package using:
# source("data-raw/_pre_commit_hook.R")
library(dplyr, warn.conflicts = FALSE)
devtools::load_all(quiet = TRUE)
suppressMessages(set_AMR_locale("English"))
old_globalenv <- ls(envir = globalenv())
# Save internal data to R/sysdata.rda -------------------------------------
# See 'data-raw/eucast_rules.tsv' for the EUCAST reference file
EUCAST_RULES_DF <- utils::read.delim(
file = "data-raw/eucast_rules.tsv",
skip = 10,
sep = "\t",
stringsAsFactors = FALSE,
header = TRUE,
strip.white = TRUE,
na = c(NA, "", NULL)
) %>%
# take the order of the reference.rule_group column in the original data file
mutate(
reference.rule_group = factor(reference.rule_group,
levels = unique(reference.rule_group),
ordered = TRUE
),
sorting_rule = ifelse(grepl("^Table", reference.rule, ignore.case = TRUE), 1, 2)
) %>%
arrange(
reference.rule_group,
reference.version,
sorting_rule,
reference.rule
) %>%
mutate(reference.rule_group = as.character(reference.rule_group)) %>%
select(-sorting_rule)
TRANSLATIONS <- utils::read.delim(
file = "data-raw/translations.tsv",
sep = "\t",
stringsAsFactors = FALSE,
header = TRUE,
blank.lines.skip = TRUE,
fill = TRUE,
strip.white = TRUE,
encoding = "UTF-8",
fileEncoding = "UTF-8",
na.strings = c(NA, "", NULL),
allowEscapes = TRUE, # else "\\1" will be imported as "\\\\1"
quote = ""
)
LANGUAGES_SUPPORTED_NAMES <- c(
list(en = list(exonym = "English", endonym = "English")),
lapply(
TRANSLATIONS[, which(nchar(colnames(TRANSLATIONS)) == 2), drop = FALSE],
function(x) list(exonym = x[1], endonym = x[2])
)
)
LANGUAGES_SUPPORTED <- names(LANGUAGES_SUPPORTED_NAMES)
# vectors of CoNS and CoPS, improves speed in as.mo()
create_species_cons_cops <- function(type = c("CoNS", "CoPS")) {
# Determination of which staphylococcal species are CoNS/CoPS according to:
# - Becker et al. 2014, PMID 25278577
# - Becker et al. 2019, PMID 30872103
# - Becker et al. 2020, PMID 32056452
# this function returns class <mo>
MO_staph <- AMR::microorganisms
MO_staph <- MO_staph[which(MO_staph$genus == "Staphylococcus"), , drop = FALSE]
if (type == "CoNS") {
MO_staph[which(MO_staph$species %in% c(
"coagulase-negative", "argensis", "arlettae",
"auricularis", "borealis", "caeli", "capitis", "caprae",
"carnosus", "casei", "chromogenes", "cohnii", "condimenti",
"croceilyticus",
"debuckii", "devriesei", "edaphicus", "epidermidis",
"equorum", "felis", "fleurettii", "gallinarum",
"haemolyticus", "hominis", "jettensis", "kloosii",
"lentus", "lugdunensis", "massiliensis", "microti",
"muscae", "nepalensis", "pasteuri", "petrasii",
"pettenkoferi", "piscifermentans", "pragensis", "pseudoxylosus",
"pulvereri", "rostri", "saccharolyticus", "saprophyticus",
"sciuri", "simulans", "stepanovicii", "succinus",
"ureilyticus",
"vitulinus", "vitulus", "warneri", "xylosus",
"caledonicus", "canis",
"durrellii", "lloydii"
) |
(MO_staph$species == "schleiferi" & MO_staph$subspecies %in% c("schleiferi", ""))),
"mo",
drop = TRUE
]
} else if (type == "CoPS") {
MO_staph[which(MO_staph$species %in% c(
"coagulase-positive", "coagulans",
"agnetis", "argenteus",
"cornubiensis",
"delphini", "lutrae",
"hyicus", "intermedius",
"pseudintermedius", "pseudointermedius",
"schweitzeri", "simiae",
"roterodami"
) |
(MO_staph$species == "schleiferi" & MO_staph$subspecies == "coagulans")),
"mo",
drop = TRUE
]
}
}
create_MO_fullname_lower <- function() {
MO_lookup <- AMR::microorganisms
# use this paste instead of `fullname` to work with Viridans Group Streptococci, etc.
MO_lookup$fullname_lower <- tolower(trimws(paste(
MO_lookup$genus,
MO_lookup$species,
MO_lookup$subspecies
)))
ind <- MO_lookup$genus == "" | grepl("^[(]unknown ", MO_lookup$fullname, perl = TRUE)
MO_lookup[ind, "fullname_lower"] <- tolower(MO_lookup[ind, "fullname", drop = TRUE])
MO_lookup$fullname_lower <- trimws(gsub("[^.a-z0-9/ \\-]+", "", MO_lookup$fullname_lower, perl = TRUE))
MO_lookup$fullname_lower
}
MO_CONS <- create_species_cons_cops("CoNS")
MO_COPS <- create_species_cons_cops("CoPS")
MO_STREP_ABCG <- as.mo(MO_lookup[which(MO_lookup$genus == "Streptococcus"), "mo", drop = TRUE], Lancefield = TRUE) %in% c("B_STRPT_GRPA", "B_STRPT_GRPB", "B_STRPT_GRPC", "B_STRPT_GRPG")
MO_FULLNAME_LOWER <- create_MO_fullname_lower()
MO_PREVALENT_GENERA <- c(
"Absidia", "Acholeplasma", "Acremonium", "Actinotignum", "Aedes", "Alistipes", "Alloprevotella",
"Alternaria", "Anaerosalibacter", "Ancylostoma", "Angiostrongylus", "Anisakis", "Anopheles",
"Apophysomyces", "Arachnia", "Aspergillus", "Aureobasidium", "Bacteroides", "Basidiobolus",
"Beauveria", "Bergeyella", "Blastocystis", "Blastomyces", "Borrelia", "Brachyspira", "Branhamella",
"Butyricimonas", "Candida", "Capillaria", "Capnocytophaga", "Catabacter", "Cetobacterium", "Chaetomium",
"Chlamydia", "Chlamydophila", "Chryseobacterium", "Chrysonilia", "Cladophialophora", "Cladosporium",
"Conidiobolus", "Contracaecum", "Cordylobia", "Cryptococcus", "Curvularia", "Deinococcus", "Demodex",
"Dermatobia", "Diphyllobothrium", "Dirofilaria", "Dysgonomonas", "Echinostoma", "Elizabethkingia",
"Empedobacter", "Enterobius", "Exophiala", "Exserohilum", "Fasciola", "Flavobacterium", "Fonsecaea",
"Fusarium", "Fusobacterium", "Giardia", "Haloarcula", "Halobacterium", "Halococcus", "Hendersonula",
"Heterophyes", "Histoplasma", "Hymenolepis", "Hypomyces", "Hysterothylacium", "Lelliottia",
"Leptosphaeria", "Leptotrichia", "Lucilia", "Lumbricus", "Malassezia", "Malbranchea", "Metagonimus",
"Microsporum", "Mortierella", "Mucor", "Mycocentrospora", "Mycoplasma", "Myroides", "Necator",
"Nectria", "Ochroconis", "Odoribacter", "Oesophagostomum", "Oidiodendron", "Opisthorchis",
"Ornithobacterium", "Parabacteroides", "Pediculus", "Pedobacter", "Phlebotomus", "Phocaeicola",
"Phocanema", "Phoma", "Piedraia", "Pithomyces", "Pityrosporum", "Porphyromonas", "Prevotella",
"Pseudallescheria", "Pseudoterranova", "Pulex", "Rhizomucor", "Rhizopus", "Rhodotorula", "Riemerella",
"Saccharomyces", "Sarcoptes", "Scolecobasidium", "Scopulariopsis", "Scytalidium", "Sphingobacterium",
"Spirometra", "Spiroplasma", "Sporobolomyces", "Stachybotrys", "Streptobacillus", "Strongyloides",
"Syngamus", "Taenia", "Tannerella", "Tenacibaculum", "Terrimonas", "Toxocara", "Treponema", "Trichinella",
"Trichobilharzia", "Trichoderma", "Trichomonas", "Trichophyton", "Trichosporon", "Trichostrongylus",
"Trichuris", "Tritirachium", "Trombicula", "Tunga", "Ureaplasma", "Victivallis", "Wautersiella",
"Weeksella", "Wuchereria"
)
# antibiotic groups
# (these will also be used for eucast_rules() and understanding data-raw/eucast_rules.tsv)
globalenv_before_ab <- c(ls(envir = globalenv()), "globalenv_before_ab")
AB_AMINOGLYCOSIDES <- antibiotics %>%
filter(group %like% "aminoglycoside") %>%
pull(ab)
AB_AMINOPENICILLINS <- as.ab(c("AMP", "AMX"))
AB_ANTIFUNGALS <- AB_lookup %>%
filter(group %like% "antifungal") %>%
pull(ab)
AB_ANTIMYCOBACTERIALS <- AB_lookup %>%
filter(group %like% "antimycobacterial") %>%
pull(ab)
AB_CARBAPENEMS <- antibiotics %>%
filter(group %like% "carbapenem") %>%
pull(ab)
AB_CEPHALOSPORINS <- antibiotics %>%
filter(group %like% "cephalosporin") %>%
pull(ab)
AB_CEPHALOSPORINS_1ST <- antibiotics %>%
filter(group %like% "cephalosporin.*1") %>%
pull(ab)
AB_CEPHALOSPORINS_2ND <- antibiotics %>%
filter(group %like% "cephalosporin.*2") %>%
pull(ab)
AB_CEPHALOSPORINS_3RD <- antibiotics %>%
filter(group %like% "cephalosporin.*3") %>%
pull(ab)
AB_CEPHALOSPORINS_4TH <- antibiotics %>%
filter(group %like% "cephalosporin.*4") %>%
pull(ab)
AB_CEPHALOSPORINS_5TH <- antibiotics %>%
filter(group %like% "cephalosporin.*5") %>%
pull(ab)
AB_CEPHALOSPORINS_EXCEPT_CAZ <- AB_CEPHALOSPORINS[AB_CEPHALOSPORINS != "CAZ"]
AB_FLUOROQUINOLONES <- antibiotics %>%
filter(atc_group2 %like% "fluoroquinolone" | (group %like% "quinolone" & is.na(atc_group2))) %>%
pull(ab)
AB_GLYCOPEPTIDES <- antibiotics %>%
filter(group %like% "glycopeptide") %>%
pull(ab)
AB_LIPOGLYCOPEPTIDES <- as.ab(c("DAL", "ORI", "TLV")) # dalba/orita/tela
AB_GLYCOPEPTIDES_EXCEPT_LIPO <- AB_GLYCOPEPTIDES[!AB_GLYCOPEPTIDES %in% AB_LIPOGLYCOPEPTIDES]
AB_LINCOSAMIDES <- antibiotics %>%
filter(atc_group2 %like% "lincosamide" | (group %like% "lincosamide" & is.na(atc_group2))) %>%
pull(ab)
AB_MACROLIDES <- antibiotics %>%
filter(atc_group2 %like% "macrolide" | (group %like% "macrolide" & is.na(atc_group2))) %>%
pull(ab)
AB_OXAZOLIDINONES <- antibiotics %>%
filter(group %like% "oxazolidinone") %>%
pull(ab)
AB_PENICILLINS <- antibiotics %>%
filter(group %like% "penicillin") %>%
pull(ab)
AB_POLYMYXINS <- antibiotics %>%
filter(group %like% "polymyxin") %>%
pull(ab)
AB_QUINOLONES <- antibiotics %>%
filter(group %like% "quinolone") %>%
pull(ab)
AB_STREPTOGRAMINS <- antibiotics %>%
filter(atc_group2 %like% "streptogramin") %>%
pull(ab)
AB_TETRACYCLINES <- antibiotics %>%
filter(group %like% "tetracycline") %>%
pull(ab)
AB_TETRACYCLINES_EXCEPT_TGC <- AB_TETRACYCLINES[AB_TETRACYCLINES != "TGC"]
AB_TRIMETHOPRIMS <- antibiotics %>%
filter(group %like% "trimethoprim") %>%
pull(ab)
AB_UREIDOPENICILLINS <- as.ab(c("PIP", "TZP", "AZL", "MEZ"))
AB_BETALACTAMS <- c(AB_PENICILLINS, AB_CEPHALOSPORINS, AB_CARBAPENEMS)
# this will be used for documentation:
DEFINED_AB_GROUPS <- ls(envir = globalenv())
DEFINED_AB_GROUPS <- DEFINED_AB_GROUPS[!DEFINED_AB_GROUPS %in% globalenv_before_ab]
create_AB_lookup <- function() {
AB_lookup <- AMR::antibiotics
AB_lookup$generalised_name <- generalise_antibiotic_name(AB_lookup$name)
AB_lookup$generalised_synonyms <- lapply(AB_lookup$synonyms, generalise_antibiotic_name)
AB_lookup$generalised_abbreviations <- lapply(AB_lookup$abbreviations, generalise_antibiotic_name)
AB_lookup$generalised_loinc <- lapply(AB_lookup$loinc, generalise_antibiotic_name)
AB_lookup$generalised_all <- unname(lapply(
as.list(as.data.frame(t(AB_lookup[,
c(
"ab", "atc", "cid", "name",
colnames(AB_lookup)[colnames(AB_lookup) %like% "generalised"]
),
drop = FALSE
]),
stringsAsFactors = FALSE
)),
function(x) {
x <- generalise_antibiotic_name(unname(unlist(x)))
x[x != ""]
}
))
AB_lookup[, colnames(AB_lookup)[colnames(AB_lookup) %like% "^generalised"]]
}
AB_LOOKUP <- create_AB_lookup()
# Export to package as internal data ----
usethis::ui_info(paste0("Saving {usethis::ui_value('sysdata.rda')} to {usethis::ui_value('R/')}"))
suppressMessages(usethis::use_data(EUCAST_RULES_DF,
TRANSLATIONS,
LANGUAGES_SUPPORTED_NAMES,
LANGUAGES_SUPPORTED,
MO_CONS,
MO_COPS,
MO_STREP_ABCG,
MO_FULLNAME_LOWER,
MO_PREVALENT_GENERA,
AB_LOOKUP,
AB_AMINOGLYCOSIDES,
AB_AMINOPENICILLINS,
AB_ANTIFUNGALS,
AB_ANTIMYCOBACTERIALS,
AB_CARBAPENEMS,
AB_CEPHALOSPORINS,
AB_CEPHALOSPORINS_1ST,
AB_CEPHALOSPORINS_2ND,
AB_CEPHALOSPORINS_3RD,
AB_CEPHALOSPORINS_4TH,
AB_CEPHALOSPORINS_5TH,
AB_CEPHALOSPORINS_EXCEPT_CAZ,
AB_FLUOROQUINOLONES,
AB_LIPOGLYCOPEPTIDES,
AB_GLYCOPEPTIDES,
AB_GLYCOPEPTIDES_EXCEPT_LIPO,
AB_LINCOSAMIDES,
AB_MACROLIDES,
AB_OXAZOLIDINONES,
AB_PENICILLINS,
AB_POLYMYXINS,
AB_QUINOLONES,
AB_STREPTOGRAMINS,
AB_TETRACYCLINES,
AB_TETRACYCLINES_EXCEPT_TGC,
AB_TRIMETHOPRIMS,
AB_UREIDOPENICILLINS,
AB_BETALACTAMS,
DEFINED_AB_GROUPS,
internal = TRUE,
overwrite = TRUE,
version = 2,
compress = "xz"
))
# Export data sets to the repository in different formats -----------------
for (pkg in c("haven", "openxlsx", "arrow")) {
if (!pkg %in% rownames(utils::installed.packages())) {
message("NOTE: package '", pkg, "' not installed! Ignoring export where this package is required.")
}
}
if ("digest" %in% rownames(utils::installed.packages())) {
md5 <- function(object) digest::digest(object, "md5")
} else {
# will write all files anyway, since MD5 hash cannot be determined
md5 <- function(object) "unknown-md5-hash"
}
write_md5 <- function(object) {
conn <- file(paste0("data-raw/", deparse(substitute(object)), ".md5"))
writeLines(md5(object), conn)
close(conn)
}
changed_md5 <- function(object) {
tryCatch(
{
conn <- file(paste0("data-raw/", deparse(substitute(object)), ".md5"))
compared <- md5(object) != readLines(con = conn)
close(conn)
compared
},
error = function(e) TRUE
)
}
# give official names to ABs and MOs
rsi <- rsi_translation %>%
mutate(mo_name = mo_name(mo, language = NULL), .after = mo) %>%
mutate(ab_name = ab_name(ab, language = NULL), .after = ab)
if (changed_md5(rsi)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('rsi_translation')} to {usethis::ui_value('data-raw/')}"))
write_md5(rsi)
try(saveRDS(rsi, "data-raw/rsi_translation.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(rsi, "data-raw/rsi_translation.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(rsi, "data-raw/rsi_translation.sas"), silent = TRUE)
try(haven::write_sav(rsi, "data-raw/rsi_translation.sav"), silent = TRUE)
try(haven::write_dta(rsi, "data-raw/rsi_translation.dta"), silent = TRUE)
try(openxlsx::write.xlsx(rsi, "data-raw/rsi_translation.xlsx"), silent = TRUE)
try(arrow::write_feather(rsi, "data-raw/rsi_translation.feather"), silent = TRUE)
try(arrow::write_parquet(rsi, "data-raw/rsi_translation.parquet"), silent = TRUE)
}
if (changed_md5(microorganisms)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('microorganisms')} to {usethis::ui_value('data-raw/')}"))
write_md5(microorganisms)
try(saveRDS(microorganisms, "data-raw/microorganisms.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(mo, "data-raw/microorganisms.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
max_50_snomed <- sapply(microorganisms$snomed, function(x) paste(x[seq_len(min(50, length(x), na.rm = TRUE))], collapse = " "))
mo <- microorganisms
mo$snomed <- max_50_snomed
mo <- dplyr::mutate_if(mo, ~ !is.numeric(.), as.character)
try(haven::write_sas(mo, "data-raw/microorganisms.sas"), silent = TRUE)
try(haven::write_sav(mo, "data-raw/microorganisms.sav"), silent = TRUE)
try(haven::write_dta(mo, "data-raw/microorganisms.dta"), silent = TRUE)
try(openxlsx::write.xlsx(mo, "data-raw/microorganisms.xlsx"), silent = TRUE)
try(arrow::write_feather(microorganisms, "data-raw/microorganisms.feather"), silent = TRUE)
try(arrow::write_parquet(microorganisms, "data-raw/microorganisms.parquet"), silent = TRUE)
}
if (changed_md5(microorganisms.old)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('microorganisms.old')} to {usethis::ui_value('data-raw/')}"))
write_md5(microorganisms.old)
try(saveRDS(microorganisms.old, "data-raw/microorganisms.old.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(microorganisms.old, "data-raw/microorganisms.old.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(microorganisms.old, "data-raw/microorganisms.old.sas"), silent = TRUE)
try(haven::write_sav(microorganisms.old, "data-raw/microorganisms.old.sav"), silent = TRUE)
try(haven::write_dta(microorganisms.old, "data-raw/microorganisms.old.dta"), silent = TRUE)
try(openxlsx::write.xlsx(microorganisms.old, "data-raw/microorganisms.old.xlsx"), silent = TRUE)
try(arrow::write_feather(microorganisms.old, "data-raw/microorganisms.old.feather"), silent = TRUE)
try(arrow::write_parquet(microorganisms.old, "data-raw/microorganisms.old.parquet"), silent = TRUE)
}
ab <- dplyr::mutate_if(antibiotics, ~ !is.numeric(.), as.character)
if (changed_md5(ab)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('antibiotics')} to {usethis::ui_value('data-raw/')}"))
write_md5(ab)
try(saveRDS(antibiotics, "data-raw/antibiotics.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(antibiotics, "data-raw/antibiotics.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(ab, "data-raw/antibiotics.sas"), silent = TRUE)
try(haven::write_sav(ab, "data-raw/antibiotics.sav"), silent = TRUE)
try(haven::write_dta(ab, "data-raw/antibiotics.dta"), silent = TRUE)
try(openxlsx::write.xlsx(ab, "data-raw/antibiotics.xlsx"), silent = TRUE)
try(arrow::write_feather(antibiotics, "data-raw/antibiotics.feather"), silent = TRUE)
try(arrow::write_parquet(antibiotics, "data-raw/antibiotics.parquet"), silent = TRUE)
}
av <- dplyr::mutate_if(antivirals, ~ !is.numeric(.), as.character)
if (changed_md5(av)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('antivirals')} to {usethis::ui_value('data-raw/')}"))
write_md5(av)
try(saveRDS(antivirals, "data-raw/antivirals.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(av, "data-raw/antivirals.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(av, "data-raw/antivirals.sas"), silent = TRUE)
try(haven::write_sav(av, "data-raw/antivirals.sav"), silent = TRUE)
try(haven::write_dta(av, "data-raw/antivirals.dta"), silent = TRUE)
try(openxlsx::write.xlsx(av, "data-raw/antivirals.xlsx"), silent = TRUE)
try(arrow::write_feather(antivirals, "data-raw/antivirals.feather"), silent = TRUE)
try(arrow::write_parquet(antivirals, "data-raw/antivirals.parquet"), silent = TRUE)
}
# give official names to ABs and MOs
intrinsicR <- data.frame(
microorganism = mo_name(intrinsic_resistant$mo, language = NULL),
antibiotic = ab_name(intrinsic_resistant$ab, language = NULL),
stringsAsFactors = FALSE
)
if (changed_md5(intrinsicR)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('intrinsic_resistant')} to {usethis::ui_value('data-raw/')}"))
write_md5(intrinsicR)
try(saveRDS(intrinsicR, "data-raw/intrinsic_resistant.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(intrinsicR, "data-raw/intrinsic_resistant.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(intrinsicR, "data-raw/intrinsic_resistant.sas"), silent = TRUE)
try(haven::write_sav(intrinsicR, "data-raw/intrinsic_resistant.sav"), silent = TRUE)
try(haven::write_dta(intrinsicR, "data-raw/intrinsic_resistant.dta"), silent = TRUE)
try(openxlsx::write.xlsx(intrinsicR, "data-raw/intrinsic_resistant.xlsx"), silent = TRUE)
try(arrow::write_feather(intrinsicR, "data-raw/intrinsic_resistant.feather"), silent = TRUE)
try(arrow::write_parquet(intrinsicR, "data-raw/intrinsic_resistant.parquet"), silent = TRUE)
}
if (changed_md5(dosage)) {
usethis::ui_info(paste0("Saving {usethis::ui_value('dosage')} to {usethis::ui_value('data-raw/')}"))
write_md5(dosage)
try(saveRDS(dosage, "data-raw/dosage.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(dosage, "data-raw/dosage.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(dosage, "data-raw/dosage.sas"), silent = TRUE)
try(haven::write_sav(dosage, "data-raw/dosage.sav"), silent = TRUE)
try(haven::write_dta(dosage, "data-raw/dosage.dta"), silent = TRUE)
try(openxlsx::write.xlsx(dosage, "data-raw/dosage.xlsx"), silent = TRUE)
try(arrow::write_feather(dosage, "data-raw/dosage.feather"), silent = TRUE)
try(arrow::write_parquet(dosage, "data-raw/dosage.parquet"), silent = TRUE)
}
suppressMessages(reset_AMR_locale())
# remove leftovers from global env
current_globalenv <- ls(envir = globalenv())
rm(list = current_globalenv[!current_globalenv %in% old_globalenv])
rm(current_globalenv)
devtools::load_all(quiet = TRUE)
suppressMessages(set_AMR_locale("English"))
# Update URLs -------------------------------------------------------------
usethis::ui_info("Checking URLs for redirects")
invisible(capture.output(urlchecker::url_update()))
# Document pkg ------------------------------------------------------------
usethis::ui_info("Documenting package")
suppressMessages(devtools::document(quiet = TRUE))
# Style pkg ---------------------------------------------------------------
usethis::ui_info("Styling package")
invisible(capture.output(styler::style_pkg(
style = styler::tidyverse_style,
filetype = c("R", "Rmd")
)))
invisible(capture.output(styler::style_dir(
path = "inst", # unit tests
style = styler::tidyverse_style,
filetype = c("R", "Rmd")
)))
# Finished ----------------------------------------------------------------
usethis::ui_done("All done")
suppressMessages(reset_AMR_locale())
+1 -1
View File
@@ -1 +1 @@
4f082a7952a37133305f64d6f711e81e
79ed9c5d9ddd2c270a5bbb579a920992
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -518
View File
@@ -1,519 +1,2 @@
"ab" "cid" "name" "group" "atc" "atc_group1" "atc_group2" "abbreviations" "synonyms" "oral_ddd" "oral_units" "iv_ddd" "iv_units" "loinc"
"AMA" 4649 "4-aminosalicylic acid" "Antimycobacterials" "J04AA01" "Drugs for treatment of tuberculosis" "Aminosalicylic acid and derivatives" "" "c(\"aminopar\", \"aminosalicylic\", \"aminosalicylic acid\", \"aminosalyl\", \"aminox\", \"apacil\", \"deapasil\", \"entepas\", \"ferrosan\", \"gabbropas\", \"helipidyl\", \"hellipidyl\", \"neopasalate\", \"osacyl\", \"pamacyl\", \"pamisyl\", \"paramycin\", \"parasal\", \"parasalicil\", \"parasalindon\", \"pasalon\", \"pasara\", \"pascorbic\", \"pasdium\", \"paser granules\", \"paskalium\", \"pasmed\", \"pasnodia\", \"pasolac\", \"propasa\", \"rezipas\", \"teebacin\", \"wln: zr cq dvq\")" 12 "g" "character(0)"
"FCT" 3366 "5-fluorocytosine" "Antifungals/antimycotics" "D01AE21" "Antifungals for topical use" "Other antifungals for topical use" "c(\"5flc\", \"fcu\", \"fluo\", \"fluy\")" "c(\"alcobon\", \"ancobon\", \"ancotil\", \"ancotyl\", \"flucitosina\", \"flucystine\", \"flucytosin\", \"flucytosine\", \"flucytosinum\", \"flucytosone\", \"fluocytosine\", \"fluorcytosine\")" "c(\"10974-4\", \"23805-5\", \"25142-1\", \"25143-9\", \"3639-2\", \"46218-4\")"
"ACM" 6450012 "Acetylmidecamycin" "Macrolides/lincosamides" "" "" ""
"ASP" 49787020 "Acetylspiramycin" "Macrolides/lincosamides" "" "c(\"acetylspiramycin\", \"foromacidin b\", \"spiramycin ii\")" "character(0)"
"ALS" 8954 "Aldesulfone sodium" "Other antibacterials" "J04BA03" "Drugs for treatment of lepra" "Drugs for treatment of lepra" "" "c(\"adesulfone sodium\", \"aldapsone\", \"aldesulfona sodica\", \"aldesulfone\", \"aldesulfone sodique\", \"aldesulfone sodium\", \"diamidin\", \"diasone\", \"diasone sodium\", \"diazon\", \"novotrone\", \"sodium aldesulphone\", \"sodium sulfoxone\", \"sulfoxone sodium\")" 0.33 "g" "character(0)"
"AMK" 37768 "Amikacin" "Aminoglycosides" "c(\"D06AX12\", \"J01GB06\", \"S01AA21\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "c(\"ak\", \"ami\", \"amik\", \"amk\", \"an\")" "c(\"amicacin\", \"amikacillin\", \"amikacin\", \"amikacin base\", \"amikacin dihydrate\", \"amikacin sulfate\", \"amikacina\", \"amikacine\", \"amikacinum\", \"amikavet\", \"amikin\", \"amiklin\", \"amikozit\", \"amukin\", \"arikace\", \"briclin\", \"lukadin\", \"mikavir\", \"pierami\", \"potentox\")" 1 "g" "c(\"13546-7\", \"15098-7\", \"17798-0\", \"31097-9\", \"31098-7\", \"31099-5\", \"3319-1\", \"3320-9\", \"3321-7\", \"35669-1\", \"50802-8\", \"50803-6\", \"56628-1\", \"59378-0\", \"80972-3\")"
"AKF" "Amikacin/fosfomycin" "Aminoglycosides" "" "" ""
"AMX" 33613 "Amoxicillin" "Beta-lactams/penicillins" "J01CA04" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"ac\", \"amox\", \"amx\")" "c(\"actimoxi\", \"amoclen\", \"amolin\", \"amopen\", \"amopenixin\", \"amoxibiotic\", \"amoxicaps\", \"amoxicilina\", \"amoxicillin\", \"amoxicilline\", \"amoxicillinum\", \"amoxiden\", \"amoxil\", \"amoxivet\", \"amoxy\", \"amoxycillin\", \"anemolin\", \"aspenil\", \"biomox\", \"bristamox\", \"cemoxin\", \"clamoxyl\", \"delacillin\", \"dispermox\", \"efpenix\", \"flemoxin\", \"hiconcil\", \"histocillin\", \"hydroxyampicillin\", \"ibiamox\", \"imacillin\", \"lamoxy\", \"metafarma capsules\", \"metifarma capsules\", \"moxacin\", \"moxatag\", \"ospamox\", \"pamoxicillin\",
\"piramox\", \"robamox\", \"sawamox pm\", \"tolodina\", \"unicillin\", \"utimox\", \"vetramox\")" 1.5 "g" 3 "g" "c(\"16365-9\", \"25274-2\", \"3344-9\", \"80133-2\")"
"AMC" 23665637 "Amoxicillin/clavulanic acid" "Beta-lactams/penicillins" "J01CR02" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"a/c\", \"amcl\", \"aml\", \"aug\", \"xl\")" "c(\"amocla\", \"amoclan\", \"amoclav\", \"amoxsiklav\", \"augmentan\", \"augmentin\", \"augmentin xr\", \"augmentine\", \"auspilic\", \"clamentin\", \"clamobit\", \"clavamox\", \"clavinex\", \"clavoxilin plus\", \"clavulin\", \"clavumox\", \"coamoxiclav\", \"eumetinex\", \"kmoxilin\", \"spectramox\", \"spektramox\", \"viaclav\", \"xiclav\")" 1.5 "g" 3 "g" "character(0)"
"AXS" 465441 "Amoxicillin/sulbactam" "Beta-lactams/penicillins" "" "" ""
"AMB" 5280965 "Amphotericin B" "Antifungals/antimycotics" "c(\"A01AB04\", \"A07AA07\", \"G01AA03\", \"J02AA01\")" "Antimycotics for systemic use" "Antibiotics" "c(\"amf\", \"amfb\", \"amph\")" "c(\"abelcet\", \"abelecet\", \"ambisome\", \"amfotericina b\", \"amphocin\", \"amphomoronal\", \"amphortericin b\", \"amphotec\", \"amphotericin\", \"amphotericin b\", \"amphotericine b\", \"amphotericinum b\", \"amphozone\", \"anfotericine b\", \"fungilin\", \"fungisome\", \"fungisone\", \"fungizone\", \"halizon\")" 40 "mg" 35 "mg" "c(\"16370-9\", \"3353-0\", \"3354-8\", \"40707-2\", \"40757-7\", \"49859-2\")"
"AMH" "Amphotericin B-high" "Aminoglycosides" "c(\"amfo b high\", \"amhl\", \"ampho b high\", \"amphotericin high\")" "" ""
"AMP" 6249 "Ampicillin" "Beta-lactams/penicillins" "c(\"J01CA01\", \"S01AA19\")" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"am\", \"amp\", \"ampi\")" "c(\"acillin\", \"adobacillin\", \"amblosin\", \"amcill\", \"amfipen\", \"amfipen v\", \"amipenix s\", \"ampichel\", \"ampicil\", \"ampicilina\", \"ampicillin\", \"ampicillin a\", \"ampicillin acid\", \"ampicillin anhydrate\", \"ampicillin anhydrous\", \"ampicillin base\", \"ampicillin sodium\", \"ampicillina\", \"ampicilline\", \"ampicillinum\", \"ampicin\", \"ampifarm\", \"ampikel\", \"ampimed\", \"ampipenin\", \"ampiscel\", \"ampisyn\", \"ampivax\", \"ampivet\", \"amplacilina\", \"amplin\", \"amplipenyl\", \"amplisom\", \"amplital\", \"anhydrous ampicillin\", \"austrapen\",
\"binotal\", \"bonapicillin\", \"britacil\", \"campicillin\", \"copharcilin\", \"delcillin\", \"deripen\", \"divercillin\", \"doktacillin\", \"duphacillin\", \"grampenil\", \"guicitrina\", \"guicitrine\", \"lifeampil\", \"marcillin\", \"morepen\", \"norobrittin\", \"nuvapen\", \"olin kid\", \"omnipen\", \"orbicilina\", \"pen a oral\", \"pen ampil\", \"penbristol\", \"penbritin\", \"penbritin paediatric\", \"penbritin syrup\", \"penbrock\", \"penicline\", \"penimic\", \"pensyn\", \"pentrex\", \"pentrexl\", \"pentrexyl\", \"pentritin\", \"pfizerpen a\", \"polycillin\", \"polyflex\",
\"ponecil\", \"princillin\", \"principen\", \"qidamp\", \"racenacillin\", \"rosampline\", \"roscillin\", \"semicillin\", \"semicillin r\", \"servicillin\", \"sumipanto\", \"synpenin\", \"texcillin\", \"tokiocillin\", \"tolomol\", \"totacillin\", \"totalciclina\", \"totapen\", \"trifacilina\", \"ukapen\", \"ultrabion\", \"ultrabron\", \"vampen\", \"viccillin\", \"viccillin s\", \"vidocillin\", \"wypicil\")" 2 "g" 6 "g" "c(\"21066-6\", \"3355-5\", \"33562-0\", \"33919-2\", \"43883-8\", \"43884-6\", \"87604-5\")"
"SAM" 119561 "Ampicillin/sulbactam" "Beta-lactams/penicillins" "J01CR01" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"a/s\", \"ab\", \"ams\", \"amsu\", \"apsu\", \"sam\")" "" 6 "g" ""
"AMR" 73341 "Amprolium" "Other antibacterials" "" "c(\"amprocidum\", \"amprolio\", \"amprolium\", \"amprovine\")" "character(0)"
"ANI" 166548 "Anidulafungin" "Antifungals/antimycotics" "J02AX06" "Antimycotics for systemic use" "Other antimycotics for systemic use" "anid" "c(\"anidulafungin\", \"anidulafungina\", \"anidulafungine\", \"anidulafunginum\", \"ecalta\", \"eraxis\")" 0.1 "g" "58420-1"
"APL" 6602341 "Apalcillin" "Beta-lactams/penicillins" "" "c(\"apalcilina\", \"apalcillin\", \"apalcilline\", \"apalcillinum\")" "character(0)"
"APR" 3081545 "Apramycin" "Aminoglycosides" "" "c(\"ambylan\", \"apralan\", \"apramicina\", \"apramycin\", \"apramycine\", \"apramycinum\", \"nebramycin ii\")" "character(0)"
"ARB" 68682 "Arbekacin" "Aminoglycosides" "J01GB12" "" "c(\"arbekacin\", \"arbekacina\", \"arbekacine\", \"arbekacini sulfas\", \"arbekacinum\", \"habekacin\", \"haberacin\")" 0.2 "g" "character(0)"
"APX" 71961 "Aspoxicillin" "Beta-lactams/penicillins" "J01CA19" "" "c(\"aspoxicilina\", \"aspoxicillan\", \"aspoxicillin\", \"aspoxicilline\", \"aspoxicillinum\")" 4 "g" "character(0)"
"AST" 5284517 "Astromicin" "Aminoglycosides" "" "c(\"astromicin\", \"astromicin a\", \"astromicina\", \"astromicine\", \"astromicinum\", \"fortimicin a\")" "character(0)"
"AVB" 9835049 "Avibactam" "Beta-lactams/penicillins" "" "c(\"avibactam\", \"avibactam free acid\")" "character(0)"
"AVI" 71674 "Avilamycin" "Other antibacterials" "" "c(\"avilamycin\", \"avilamycina\", \"avilamycine\", \"avilamycinum\", \"surmax\")" "character(0)"
"AVO" 16131159 "Avoparcin" "Glycopeptides" "" "" ""
"AZD" 15574941 "Azidocillin" "Beta-lactams/penicillins" "J01CE04" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"azidocilina\", \"azidocillin\", \"azidocillina\", \"azidocilline\", \"azidocillinum\")" 1.5 "g" "character(0)"
"AZM" 447043 "Azithromycin" "Macrolides/lincosamides" "c(\"J01FA10\", \"S01AA26\")" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"az\", \"azi\", \"azit\", \"azm\")" "c(\"aritromicina\", \"azasite\", \"azenil\", \"azifast\", \"azigram\", \"azimakrol\", \"azithramycine\", \"azithromycin\", \"azithromycine\", \"azithromycinum\", \"azitrocin\", \"azitromax\", \"azitromicina\", \"azitromicine\", \"azitromin\", \"aziwok\", \"aztrin\", \"azyter\", \"azythromycin\", \"hemomycin\", \"misultina\", \"mixoterin\", \"setron\", \"sumamed\", \"tromix\", \"trulimax\", \"zentavion\", \"zithrax\", \"zithromac\", \"zithromax\", \"zithromax iv\", \"zithromycin\", \"zitrim\", \"zitromax\", \"zitrotek\", \"zmax sr\")" 0.3 "g" 0.5 "g" "c(\"16420-2\", \"25233-8\")"
"AZL" 6479523 "Azlocillin" "Beta-lactams/penicillins" "J01CA09" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"az\", \"azl\", \"azlo\")" "" 12 "g" ""
"ATM" 5742832 "Aztreonam" "Beta-lactams/penicillins" "J01DF01" "Other beta-lactam antibacterials" "Monobactams" "c(\"at\", \"atm\", \"azm\", \"azt\", \"aztr\")" "c(\"azactam\", \"azetreonam\", \"azthreonam\", \"aztreonam\", \"primbactam\")" 4 "g" "c(\"16423-6\", \"25234-6\", \"3369-6\")"
"AZA" "Aztreonam/avibactam" "Beta-lactams/penicillins" "" "" ""
"ANC" "Aztreonam/nacubactam" "Beta-lactams/penicillins" "" "" ""
"BAM" 441397 "Bacampicillin" "Beta-lactams/penicillins" "J01CA06" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"bacampicilina\", \"bacampicillin\", \"bacampicilline\", \"bacampicillinum\", \"penglobe\")" 1.2 "g" "character(0)"
"BAC" 78358334 "Bacitracin zinc" "Other antibacterials" "R02AB04" "baci" "" ""
"BDQ" 5388906 "Bedaquiline" "Other antibacterials" "J04AK05" "" "c(\"bedaquiline\", \"sirturo\")" 86 "mg" "80637-2"
"BEK" 439318 "Bekanamycin" "Aminoglycosides" "J01GB13" "" "c(\"aminodeoxykanamycin\", \"becanamicina\", \"bekanamycin\", \"bekanamycine\", \"bekanamycinum\", \"nebramycin v\")" 0.6 "g" "character(0)"
"BNB" "Benzathine benzylpenicillin" "Beta-lactams/penicillins" "J01CE08" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "" 3.6 "g" ""
"BNP" 64725 "Benzathine phenoxymethylpenicillin" "Beta-lactams/penicillins" "J01CE10" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"bicillin v\", \"biphecillin\")" 2 "g" "character(0)"
"PEN" 5904 "Benzylpenicillin" "Beta-lactams/penicillins" "c(\"J01CE01\", \"S01AA14\")" "Combinations of antibacterials" "Combinations of antibacterials" "c(\"bepe\", \"pen\", \"peni\", \"peni g\", \"penicillin\", \"penicillin g\", \"pg\")" "c(\"abbocillin\", \"ayercillin\", \"bencilpenicilina\", \"benzopenicillin\", \"benzyl penicillin\", \"benzylpenicillin\", \"benzylpenicillin g\", \"benzylpenicilline\", \"benzylpenicillinum\", \"bicillin\", \"cillora\", \"cilloral\", \"cilopen\", \"compocillin g\", \"cosmopen\", \"dropcillin\", \"free penicillin g\", \"free penicillin ii\", \"galofak\", \"gelacillin\", \"liquacillin\", \"megacillin\", \"pencillin g\", \"penicillin\", \"penicilling\", \"pentids\", \"permapen\", \"pfizerpen\", \"pfizerpen g\", \"pharmacillin\", \"pradupen\", \"specilline g\", \"ursopen\"
)" 3.6 "g" "3913-1"
"BES" 10178705 "Besifloxacin" "Quinolones" "S01AE08" "" "besifloxacin" "character(0)"
"BIA" 71339 "Biapenem" "Carbapenems" "J01DH05" "" "c(\"biapenem\", \"biapenern\", \"bipenem\", \"omegacin\")" 1.2 "g" "character(0)"
"BCZ" 65807 "Bicyclomycin" "Other antibacterials" "c(\"\", \"bicozamycin\")" "c(\"aizumycin\", \"bacfeed\", \"bacteron\", \"bicozamicina\", \"bicozamycin\", \"bicozamycine\", \"bicozamycinum\")" "character(0)"
"BDP" 68760 "Brodimoprim" "Trimethoprims" "J01EA02" "Sulfonamides and trimethoprim" "Trimethoprim and derivatives" "" "c(\"brodimoprim\", \"brodimoprima\", \"brodimoprime\", \"brodimoprimum\", \"bromdimoprim\", \"hyprim\", \"unitrim\")" 0.2 "g" "character(0)"
"BUT" 47472 "Butoconazole" "Antifungals/antimycotics" "G01AF15" "" "c(\"butaconazole\", \"butoconazol\", \"butoconazole\", \"butoconazolum\", \"compositenstarke\", \"dahlin\", \"femstat\", \"gynofort\", \"polyfructosanum\")" "character(0)"
"CDZ" 44242317 "Cadazolid" "Oxazolidinones" "" "cadazolid" "character(0)"
"CLA" "Calcium aminosalicylate" "Antimycobacterials" "J04AA03" "Drugs for treatment of tuberculosis" "Aminosalicylic acid and derivatives" "" "" 15 "g" ""
"CAP" 135565060 "Capreomycin" "Antimycobacterials" "J04AB30" "Drugs for treatment of tuberculosis" "Antibiotics" "c(\"\", \"capr\")" "" 1 "g" ""
"CRB" 20824 "Carbenicillin" "Beta-lactams/penicillins" "J01CA03" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"bar\", \"carb\", \"cb\")" "c(\"anabactyl\", \"carbenicilina\", \"carbenicillin\", \"carbenicillina\", \"carbenicilline\", \"carbenicillinum\", \"geopen\", \"pyopen\")" 12 "g" "3434-8"
"CRN" 93184 "Carindacillin" "Beta-lactams/penicillins" "J01CA05" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"carindacilina\", \"carindacillin\", \"carindacilline\", \"carindacillinum\")" 4 "g" "character(0)"
"CAR" 6540466 "Carumonam" "Other antibacterials" "J01DF02" "" "c(\"carumonam\", \"carumonamum\")" 2 "g" "character(0)"
"CAS" 2826718 "Caspofungin" "Antifungals/antimycotics" "J02AX04" "Antimycotics for systemic use" "Other antimycotics for systemic use" "casp" "c(\"cancidas\", \"capsofungin\", \"caspofungin\")" 50 "mg" "58419-3"
"CAC" 91562 "Cefacetrile" "Cephalosporins (1st gen.)" "J01DB10" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"cefacetril\", \"cefacetrile\", \"cefacetrilo\", \"cefacetrilum\", \"celospor\", \"celtol\", \"cephacetrile\", \"cristacef\", \"vetrimast\")" "character(0)"
"CEC" 51039 "Cefaclor" "Cephalosporins (2nd gen.)" "J01DC04" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"ccl\", \"cec\", \"cf\", \"cfac\", \"cfc\", \"cfcl\", \"cfr\", \"fac\")" "c(\"alenfral\", \"alfacet\", \"ceclor\", \"ceclor cd\", \"cefaclor\", \"cefaclor anhydrous\", \"cefaclor monohydrate\", \"cefacloro\", \"cefaclorum\", \"cefeaclor\", \"cephaclor\", \"dystaclor mr\", \"keflor\", \"kefral\", \"raniclor\")" 1 "g" "c(\"16564-7\", \"21149-0\")"
"CFR" 47965 "Cefadroxil" "Cephalosporins (1st gen.)" "J01DB05" "Other beta-lactam antibacterials" "First-generation cephalosporins" "c(\"cfdx\", \"cfr\", \"fad\")" "c(\"cefadrops\", \"cefadroxil\", \"cefadroxil anhydrous\", \"cefadroxilo\", \"cefadroxilum\", \"cefradroxil\", \"cephadroxil\", \"duricef\", \"sumacef\", \"ultracef\")" 2 "g" "16565-4"
"RID" 5773 "Cefaloridine" "Cephalosporins (1st gen.)" "J01DB02" "Other beta-lactam antibacterials" "First-generation cephalosporins" "cefa" "c(\"aliporina\", \"ampligram\", \"cefaloridin\", \"cefaloridina\", \"cefaloridine\", \"cefaloridinum\", \"cefalorizin\", \"ceflorin\", \"cepaloridin\", \"cepalorin\", \"cephalomycine\", \"cephaloridin\", \"cephaloridine\", \"cephaloridinum\", \"ceporan\", \"ceporin\", \"ceporine\", \"cilifor\", \"deflorin\", \"faredina\", \"floridin\", \"glaxoridin\", \"intrasporin\", \"keflodin\", \"keflordin\", \"kefloridin\", \"kefspor\", \"lloncefal\", \"loridine\", \"sasperin\", \"sefacin\", \"verolgin\", \"vioviantine\")" 3 "g" "character(0)"
"MAN" 456255 "Cefamandole" "Cephalosporins (2nd gen.)" "J01DC03" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"cfam\", \"cfmn\")" "c(\"cefadole\", \"cefamandol\", \"cefamandole\", \"cefamandolum\", \"cephadole\", \"cephamandole\", \"kefamandol\", \"kefdole\", \"mancef\")" 6 "g" "3441-3"
"CTZ" 6410758 "Cefatrizine" "Cephalosporins (1st gen.)" "J01DB07" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"bricef\", \"cefatrix\", \"cefatrizine\", \"cefatrizino\", \"cefatrizinum\", \"cepticol\", \"cetrazil\", \"latocef\", \"orosporina\", \"trizina\")" 1 "g" "character(0)"
"CZD" 71736 "Cefazedone" "Cephalosporins (1st gen.)" "J01DB06" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"cefazedon\", \"cefazedona\", \"cefazedone\", \"cefazedone acid\", \"cefazedonum\", \"refosporen\", \"refosporene\", \"refosporin\")" 3 "g" "character(0)"
"CZO" 33255 "Cefazolin" "Cephalosporins (1st gen.)" "J01DB04" "Other beta-lactam antibacterials" "First-generation cephalosporins" "c(\"cfz\", \"cfzl\", \"cz\", \"czol\", \"faz\", \"kz\")" "c(\"atirin\", \"cefamezin\", \"cefamezine\", \"cefazina\", \"cefazolin\", \"cefazolin acid\", \"cefazolina\", \"cefazoline\", \"cefazolinum\", \"cephamezine\", \"cephazolidin\", \"cephazolin\", \"cephazoline\", \"elzogram\", \"firmacef\", \"kefzol\", \"liviclina\", \"totacef\")" 3 "g" "c(\"16566-2\", \"25235-3\", \"3442-1\", \"3443-9\", \"80962-4\")"
"CFB" 127527 "Cefbuperazone" "Other antibacterials" "J01DC13" "" "c(\"cefbuperazona\", \"cefbuperazone\", \"cefbuperazonum\", \"cefbuperzaone\", \"cerbuperazone\", \"tomiporan\")" 2 "g" "character(0)"
"CCP" 6436055 "Cefcapene" "Cephalosporins (3rd gen.)" "J01DD17" "" "c(\"cefcamate\", \"cefcapene\")" 0.45 "g" "character(0)"
"CCX" 5282438 "Cefcapene pivoxil" "Cephalosporins (3rd gen.)" "" "c(\"cefcamate pivoxil\", \"cefcapene piroxil\")" "character(0)"
"CDR" 6915944 "Cefdinir" "Cephalosporins (3rd gen.)" "J01DD15" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cd\", \"cdn\", \"cdr\", \"cfd\", \"din\")" "c(\"cefdinir\", \"cefdinirum\", \"cefdinyl\", \"cefdirnir\", \"ceftinex\", \"cefzon\", \"omnicef\")" 0.6 "g" "character(0)"
"DIT" 9870843 "Cefditoren" "Cephalosporins (3rd gen.)" "J01DD16" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "cdn" "cefditoren" 0.4 "g" "character(0)"
"DIX" 6437877 "Cefditoren pivoxil" "Cephalosporins (3rd gen.)" "" "c(\"cefditoren\", \"cefditoren pi voxil\", \"cefditoren pivoxil\", \"cefditorin\", \"cefditorin pivoxil\", \"meiact\", \"spectracef\")" "character(0)"
"FEP" 5479537 "Cefepime" "Cephalosporins (4th gen.)" "J01DE01" "Other beta-lactam antibacterials" "Fourth-generation cephalosporins" "c(\"cfep\", \"cfpi\", \"cpe\", \"cpm\", \"fep\", \"pm\", \"xpm\")" "c(\"axepim\", \"cefepima\", \"cefepime\", \"cefepimum\", \"cepimax\", \"cepimex\", \"maxcef\", \"maxipime\")" 4 "g" "38363-8"
"CPC" 9567559 "Cefepime/clavulanic acid" "Cephalosporins (4th gen.)" "c(\"cicl\", \"xpml\")" "" ""
"FNC" "Cefepime/nacubactam" "Beta-lactams/penicillins" "" "" ""
"FPT" 9567558 "Cefepime/tazobactam" "Cephalosporins (4th gen.)" "" "" ""
"FPZ" "Cefepime/zidebactam" "Other antibacterials" "" "" ""
"CAT" 5487888 "Cefetamet" "Cephalosporins (3rd gen.)" "J01DD10" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "c(\"cefetamet\", \"cefetametum\", \"cepime o\", \"deacetoxycefotaxime\")" 1 "g" "character(0)"
"CPI" 5486182 "Cefetamet pivoxil" "Cephalosporins (3rd gen.)" "" "c(\"cefetamet pivoxyl\", \"globocef\")" "character(0)"
"CCL" 71719688 "Cefetecol" "Cephalosporins (4th gen.)" "c(\"\", \"cefcatacol\")" "" ""
"CZL" 193956 "Cefetrizole" "Cephalosporins (unclassified gen.)" "" "c(\"cefetrizole\", \"cefetrizolum\")" "character(0)"
"FDC" 77843966 "Cefiderocol" "Other antibacterials" "J01DI04" "" "cefiderocol" "character(0)"
"CFM" 5362065 "Cefixime" "Cephalosporins (3rd gen.)" "J01DD08" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfe\", \"cfix\", \"cfxm\", \"dcfm\", \"fix\", \"ix\")" "c(\"cefixim\", \"cefixima\", \"cefixime\", \"cefixime anhydrous\", \"cefiximum\", \"cefixoral\", \"cefspan\", \"cephoral\", \"denvar\", \"necopen\", \"suprax\", \"tricef\", \"unixime\")" 0.4 "g" "c(\"16567-0\", \"25236-1\")"
"CMX" 9570757 "Cefmenoxime" "Cephalosporins (3rd gen.)" "J01DD05" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "c(\"bestron\", \"cefmax\", \"cefmenoxima\", \"cefmenoxime\", \"cefmenoximum\")" 2 "g" "character(0)"
"CMZ" 42008 "Cefmetazole" "Cephalosporins (2nd gen.)" "J01DC09" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "" "c(\"cefmetazole\", \"cefmetazolo\", \"cefmetazolum\")" 4 "g" "character(0)"
"CNX" 71141 "Cefminox" "Other antibacterials" "J01DC12" "" "c(\"cefminox\", \"cefminoxum\")" 4 "g" "character(0)"
"DIZ" 5361871 "Cefodizime" "Cephalosporins (3rd gen.)" "J01DD09" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "c(\"cefodizima\", \"cefodizime\", \"cefodizime acid\", \"cefodizimum\", \"cefodizme\", \"diezime\", \"modivid\", \"neucef\", \"timecef\")" 2 "g" "character(0)"
"CID" 43594 "Cefonicid" "Cephalosporins (2nd gen.)" "J01DC06" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "" "c(\"cefonicid\", \"cefonicido\", \"cefonicidum\", \"monocef\")" 1 "g" "c(\"25237-9\", \"3444-7\")"
"CFP" 44187 "Cefoperazone" "Cephalosporins (3rd gen.)" "J01DD12" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfp\", \"cfpz\", \"cp\", \"cpz\", \"fop\", \"per\")" "c(\"bioperazone\", \"cefobid\", \"cefoperazine\", \"cefoperazon\", \"cefoperazone\", \"cefoperazone acid\", \"cefoperazono\", \"cefoperazonum\", \"cefozon\", \"medocef\", \"myticef\", \"pathozone\", \"peracef\")" 4 "g" "3445-4"
"CSL" "Cefoperazone/sulbactam" "Cephalosporins (3rd gen.)" "J01DD62" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "" 4 "g" ""
"CND" 43507 "Ceforanide" "Cephalosporins (2nd gen.)" "J01DC11" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "" "c(\"ceforanide\", \"ceforanido\", \"ceforanidum\", \"precef\", \"radacef\")" 4 "g" "character(0)"
"CSE" 9830519 "Cefoselis" "Cephalosporins (4th gen.)" "" "c(\"cefoselis\", \"cefoselis sulfate\", \"winsef\")" "character(0)"
"CTX" 5742673 "Cefotaxime" "Cephalosporins (3rd gen.)" "J01DD01" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfot\", \"cft\", \"cftx\", \"ct\", \"ctx\", \"fot\", \"tax\", \"xct\")" "c(\"cefotaxim\", \"cefotaxim hikma\", \"cefotaxima\", \"cefotaxime\", \"cefotaxime acid\", \"cefotaximum\", \"cephotaxime\", \"claforan\", \"omnatax\")" 4 "g" "c(\"25238-7\", \"3446-2\", \"80961-6\")"
"CTC" 9575353 "Cefotaxime/clavulanic acid" "Cephalosporins (3rd gen.)" "c(\"cxcl\", \"xctl\")" "" ""
"CTS" 9574753 "Cefotaxime/sulbactam" "Cephalosporins (3rd gen.)" "" "" ""
"CTT" 53025 "Cefotetan" "Cephalosporins (2nd gen.)" "J01DC05" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"cftt\", \"cn\", \"cte\", \"ctn\", \"ctt\", \"tans\")" "c(\"apacef\", \"cefotetan\", \"cefotetan free acid\", \"cefotetanum\")" 4 "g" "c(\"25239-5\", \"3447-0\")"
"CTF" 43708 "Cefotiam" "Cephalosporins (2nd gen.)" "J01DC07" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "" "c(\"cefotiam\", \"cefotiam?\", \"cefotiamum\", \"ceradolan\", \"ceradon\", \"haloapor\")" 1.2 "g" 4 "g" "character(0)"
"CHE" 125846 "Cefotiam hexetil" "Cephalosporins (3rd gen.)" "" "c(\"cefotiam cilexetil\", \"pansporin t\")" "character(0)"
"FOV" 9578573 "Cefovecin" "Cephalosporins (3rd gen.)" "" "" ""
"FOX" 441199 "Cefoxitin" "Cephalosporins (2nd gen.)" "J01DC01" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"cfox\", \"cfx\", \"cfxt\", \"cx\", \"fox\", \"fx\")" "c(\"cefoxitin\", \"cefoxitina\", \"cefoxitine\", \"cefoxitinum\", \"cefoxotin\", \"cephoxitin\", \"mefoxin\", \"mefoxitin\", \"rephoxitin\")" 6 "g" "c(\"25240-3\", \"3448-8\")"
"FOX1" "Cefoxitin screening" "Cephalosporins (2nd gen.)" "cfsc" "" ""
"ZOP" 9571080 "Cefozopran" "Cephalosporins (4th gen.)" "J01DE03" "" "cefozopran" 4 "g" "character(0)"
"CFZ" 68597 "Cefpimizole" "Cephalosporins (3rd gen.)" "" "c(\"cefpimizol\", \"cefpimizole\", \"cefpimizole sodium\", \"cefpimizolum\")" "character(0)"
"CPM" 636405 "Cefpiramide" "Cephalosporins (3rd gen.)" "J01DD11" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "c(\"cefpiramide\", \"cefpiramide acid\", \"cefpiramido\", \"cefpiramidum\")" 2 "g" "character(0)"
"CPO" 5479539 "Cefpirome" "Cephalosporins (4th gen.)" "J01DE02" "Other beta-lactam antibacterials" "Fourth-generation cephalosporins" "c(\"\", \"cfpr\")" "c(\"broact\", \"cefpiroma\", \"cefpirome\", \"cefpiromum\", \"cefrom\", \"cerfpirome\", \"keiten\")" 4 "g" "character(0)"
"CPD" 6335986 "Cefpodoxime" "Cephalosporins (3rd gen.)" "J01DD13" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfpd\", \"cfpo\", \"cpd\", \"pod\", \"px\")" "c(\"cefpodoxim acid\", \"cefpodoxima\", \"cefpodoxime\", \"cefpodoxime acid\", \"cefpodoximum\", \"epoxim\")" 0.4 "g" "25241-1"
"CPX" 6526396 "Cefpodoxime proxetil" "Cephalosporins (3rd gen.)" "" "c(\"cefodox\", \"cefoprox\", \"cefpodoxime proxetil\", \"cepodem\", \"orelox\", \"otreon\", \"podomexef\", \"simplicef\", \"vantin\")" "character(0)"
"CDC" "Cefpodoxime/clavulanic acid" "Cephalosporins (3rd gen.)" "c(\"\", \"cecl\")" "" ""
"CPR" 5281006 "Cefprozil" "Cephalosporins (2nd gen.)" "J01DC10" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"cpr\", \"cpz\", \"fp\")" "c(\"arzimol\", \"brisoral\", \"cefprozil\", \"cefprozil anhydrous\", \"cefprozil hydrate\", \"cefprozilo\", \"cefprozilum\", \"cefzil\", \"cronocef\", \"procef\", \"serozil\")" 1 "g" "character(0)"
"CEQ" 5464355 "Cefquinome" "Cephalosporins (4th gen.)" "" "c(\"cefquinoma\", \"cefquinome\", \"cefquinomum\", \"cobactan\")" "character(0)"
"CRD" 5284529 "Cefroxadine" "Cephalosporins (1st gen.)" "J01DB11" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"cefroxadine\", \"cefroxadino\", \"cefroxadinum\")" 2.1 "g" "character(0)"
"CFS" 656575 "Cefsulodin" "Cephalosporins (3rd gen.)" "J01DD03" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfsl\", \"cfsu\")" "c(\"cefsulodin\", \"cefsulodine\", \"cefsulodino\", \"cefsulodinum\")" 4 "g" "c(\"131-3\", \"25242-9\")"
"CSU" 68718 "Cefsumide" "Cephalosporins (unclassified gen.)" "" "c(\"cefsumide\", \"cefsumido\", \"cefsumidum\")" "character(0)"
"CPT" 56841980 "Ceftaroline" "Cephalosporins (5th gen.)" "J01DI02" "c(\"\", \"cfro\")" "c(\"teflaro\", \"zinforo\")" 1.2 "g" "character(0)"
"CPA" "Ceftaroline/avibactam" "Cephalosporins (5th gen.)" "" "" ""
"CAZ" 5481173 "Ceftazidime" "Cephalosporins (3rd gen.)" "J01DD02" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"caz\", \"cefta\", \"cfta\", \"cftz\", \"taz\", \"tz\", \"xtz\")" "c(\"ceftazidim\", \"ceftazidima\", \"ceftazidime\", \"ceftazidimum\", \"ceptaz\", \"fortaz\", \"fortum\", \"pentacef\", \"tazicef\", \"tazidime\")" 4 "g" "c(\"21151-6\", \"3449-6\", \"80960-8\")"
"CZA" 90643431 "Ceftazidime/avibactam" "Cephalosporins (3rd gen.)" "c(\"\", \"cfav\")" "c(\"avycaz\", \"zavicefta\")" ""
"CCV" 9575352 "Ceftazidime/clavulanic acid" "Cephalosporins (3rd gen.)" "J01DD52" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"czcl\", \"xtzl\")" "" 6 "g" ""
"CEM" 6537431 "Cefteram" "Cephalosporins (3rd gen.)" "J01DD18" "" "c(\"cefteram\", \"cefterame\", \"cefteramum\", \"ceftetrame\")" 0.4 "g" "character(0)"
"CPL" 5362114 "Cefteram pivoxil" "Cephalosporins (3rd gen.)" "" "c(\"cefteram pivoxil\", \"tomiron\")" "character(0)"
"CTL" 65755 "Ceftezole" "Cephalosporins (1st gen.)" "J01DB12" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"ceftezol\", \"ceftezole\", \"ceftezolo\", \"ceftezolum\", \"demethylcefazolin\")" 3 "g" "character(0)"
"CTB" 5282242 "Ceftibuten" "Cephalosporins (3rd gen.)" "J01DD14" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cb\", \"cfbu\", \"ctb\", \"tib\")" "c(\"ceftem\", \"ceftibuten\", \"ceftibuten hydrate\", \"ceftibutene\", \"ceftibuteno\", \"ceftibutenum\", \"cephem\", \"ceprifran\", \"isocef\", \"keimax\")" 0.4 "g" "character(0)"
"TIO" 6328657 "Ceftiofur" "Cephalosporins (3rd gen.)" "" "c(\"ceftiofur\", \"ceftiofurum\", \"excede\", \"excenel\", \"naxcel\")" "character(0)"
"CZX" 6533629 "Ceftizoxime" "Cephalosporins (3rd gen.)" "J01DD07" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"cfzx\", \"ctz\", \"cz\", \"czx\", \"tiz\", \"zox\")" "c(\"cefizox\", \"ceftisomin\", \"ceftix\", \"ceftizoxima\", \"ceftizoxime\", \"ceftizoximum\", \"epocelin\", \"eposerin\")" 4 "g" "c(\"25243-7\", \"3450-4\")"
"CZP" 9578661 "Ceftizoxime alapivoxil" "Cephalosporins (3rd gen.)" "" "" ""
"BPR" 135413542 "Ceftobiprole" "Cephalosporins (5th gen.)" "" "ceftobiprole" "character(0)"
"CFM1" 135413544 "Ceftobiprole medocaril" "Cephalosporins (5th gen.)" "J01DI01" "Other beta-lactam antibacterials" "Other cephalosporins and penems" "" "" 1.5 "g" ""
"CEI" "Ceftolozane/enzyme inhibitor" "Cephalosporins (5th gen.)" "J01DI54" "Other beta-lactam antibacterials" "Other cephalosporins and penems" "" "" 3 "g" ""
"CZT" "Ceftolozane/tazobactam" "Cephalosporins (5th gen.)" "" "" ""
"CRO" 5479530 "Ceftriaxone" "Cephalosporins (3rd gen.)" "J01DD04" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"axo\", \"cax\", \"cftr\", \"cro\", \"ctr\", \"frx\", \"tx\")" "c(\"biotrakson\", \"cefatriaxone\", \"cefatriaxone hydrate\", \"ceftriaxon\", \"ceftriaxona\", \"ceftriaxone\", \"ceftriaxone sodium\", \"ceftriaxonum\", \"ceftriazone\", \"cephtriaxone\", \"longacef\", \"rocefin\", \"rocephalin\", \"rocephin\", \"rocephine\", \"rophex\")" 2 "g" "c(\"25244-5\", \"3451-2\", \"80957-4\")"
"CXM" 5479529 "Cefuroxime" "Cephalosporins (2nd gen.)" "c(\"J01DC02\", \"S01AA27\")" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"cfrx\", \"cfur\", \"cfx\", \"crm\", \"cxm\", \"fur\", \"rox\", \"xm\")" "c(\"biofuroksym\", \"cefuril\", \"cefuroxim\", \"cefuroxime\", \"cefuroximine\", \"cefuroximo\", \"cefuroximum\", \"cephuroxime\", \"kefurox\", \"sharox\", \"zinacef\", \"zinacef danmark\")" 0.5 "g" 3 "g" "c(\"25245-2\", \"3452-0\", \"80608-3\", \"80617-4\")"
"CXA" 6321416 "Cefuroxime axetil" "Cephalosporins (2nd gen.)" "c(\"\", \"cfax\")" "c(\"altacef\", \"bioracef\", \"cefaks\", \"cefazine\", \"ceftin\", \"cefuroximaxetil\", \"cefuroxime axetil\", \"celocid\", \"cepazine\", \"cethixim\", \"cetoxil\", \"coliofossim\", \"elobact\", \"forcef\", \"furoxime\", \"kalcef\", \"maxitil\", \"medoxm\", \"nivador\", \"zinnat\")" "character(0)"
"CFM2" "Cefuroxime/metronidazole" "Other antibacterials" "J01RA03" "Combinations of antibacterials" "Combinations of antibacterials" "" "" ""
"ZON" 6336505 "Cefuzonam" "Other antibacterials" "" "c(\"cefuzonam\", \"cefuzonam sodium\", \"cefuzoname\", \"cefuzonamum\")" "character(0)"
"LEX" 27447 "Cephalexin" "Cephalosporins (1st gen.)" "J01DB01" "Other beta-lactam antibacterials" "First-generation cephalosporins" "c(\"\", \"cflx\")" "c(\"alcephin\", \"alexin\", \"alsporin\", \"anhydrous cefalexin\", \"anhydrous cephalexin\", \"biocef\", \"carnosporin\", \"cefablan\", \"cefadal\", \"cefadin\", \"cefadina\", \"cefaleksin\", \"cefalessina\", \"cefalexin\", \"cefalexin anhydrous\", \"cefalexina\", \"cefalexine\", \"cefalexinum\", \"cefalin\", \"cefaloto\", \"cefaseptin\", \"ceflax\", \"ceforal\", \"cefovit\", \"celexin\", \"cepastar\", \"cepexin\", \"cephacillin\", \"cephalexin\", \"cephalexin anhydrous\", \"cephalexine\", \"cephalexinum\", \"cephanasten\", \"cephaxin\", \"cephin\", \"ceporex\", \"ceporex forte\",
\"ceporexin\", \"ceporexine\", \"cerexin\", \"cerexins\", \"cophalexin\", \"durantel\", \"durantel ds\", \"erocetin\", \"factagard\", \"felexin\", \"ibilex\", \"ibrexin\", \"inphalex\", \"kefalospes\", \"keflet\", \"keflex\", \"kefolan\", \"keforal\", \"keftab\", \"kekrinal\", \"kidolex\", \"lafarine\", \"larixin\", \"lenocef\", \"lexibiotico\", \"lonflex\", \"lopilexin\", \"madlexin\", \"mamalexin\", \"mamlexin\", \"medoxine\", \"neokef\", \"neolexina\", \"novolexin\", \"optocef\", \"oracef\", \"oriphex\", \"oroxin\", \"ortisporina\", \"ospexin\", \"palitrex\", \"panixine disperdose\",
\"pectril\", \"pyassan\", \"roceph\", \"roceph distab\", \"sanaxin\", \"sartosona\", \"sencephalin\", \"sepexin\", \"servispor\", \"sialexin\", \"sinthecillin\", \"sporicef\", \"sporidex\", \"syncle\", \"synecl\", \"tepaxin\", \"tokiolexin\", \"uphalexin\", \"voxxim\", \"winlex\", \"zozarine\")" 2 "g" "c(\"21175-5\", \"3453-8\")"
"CEP" 6024 "Cephalothin" "Cephalosporins (1st gen.)" "J01DB03" "Other beta-lactam antibacterials" "First-generation cephalosporins" "c(\"cfal\", \"cflt\")" "c(\"cefalothin\", \"cefalotin\", \"cefalotina\", \"cefalotina fabra\", \"cefalotine\", \"cefalotinum\", \"cemastin\", \"cephalothinum\", \"cephalotin\", \"coaxin\", \"keflin\", \"seffin\")" 4 "g" "c(\"25246-0\", \"3454-6\")"
"HAP" 30699 "Cephapirin" "Cephalosporins (1st gen.)" "J01DB08" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"ambrocef\", \"cefadyl\", \"cefapilin\", \"cefapirin\", \"cefapirina\", \"cefapirine\", \"cefapirinum\", \"cefaprin\", \"cefaprin sodium\", \"cefatrex\", \"cefatrexyl\", \"cephapirine\", \"metricure\")" 4 "g" "10980-1"
"CED" 38103 "Cephradine" "Cephalosporins (1st gen.)" "J01DB09" "Other beta-lactam antibacterials" "First-generation cephalosporins" "c(\"cfra\", \"cfrd\")" "c(\"anspor\", \"cefradin\", \"cefradina\", \"cefradine\", \"cefradinum\", \"cekodin\", \"cephradin\", \"cephradine\", \"eskacef\", \"infexin\", \"megace f\", \"megacef\", \"sefril\", \"velocef\", \"velosef\")" 2 "g" 2 "g" "character(0)"
"CTO" 71402 "Cetocycline" "Tetracyclines" "" "c(\"cetocycline\", \"cetocyline\", \"cetotetrine\")" "character(0)"
"CHL" 5959 "Chloramphenicol" "Amphenicols" "c(\"D06AX02\", \"D10AF03\", \"G01AA05\", \"J01BA01\", \"S01AA01\", \"S02AA01\", \"S03AA08\")" "Amphenicols" "Amphenicols" "c(\"c\", \"chl\", \"chlo\", \"cl\")" "c(\"alficetyn\", \"ambofen\", \"amphenicol\", \"amphicol\", \"amseclor\", \"anacetin\", \"aquamycetin\", \"austracil\", \"austracol\", \"biocetin\", \"biophenicol\", \"catilan\", \"ch loramex\", \"chemiceticol\", \"chemicetin\", \"chemicetina\", \"chlomin\", \"chlomycol\", \"chloramex\", \"chloramfenikol\", \"chloramficin\", \"chloramfilin\", \"chloramphenicol\", \"chloramphenicole\", \"chloramphenicolum\", \"chloramsaar\", \"chlorasol\", \"chlorbiotic\", \"chloricol\", \"chlormycetin r\", \"chlornitromycin\", \"chloroamphenicol\", \"chlorocaps\", \"chlorocid\",
\"chlorocid s\", \"chlorocide\", \"chlorocidin c\", \"chlorocidin c tetran\", \"chlorocin\", \"chlorocol\", \"chlorofair\", \"chloroject l\", \"chloromax\", \"chloromycetin\", \"chloromycetny\", \"chloromyxin\", \"chloronitrin\", \"chloroptic\", \"chloroptic s.o.p\", \"chloroptic s.o.p.\", \"chlorovules\", \"chlorsig\", \"cidocetine\", \"ciplamycetin\", \"cloramfen\", \"cloramfenicol\", \"cloramfenicolo\", \"cloramficin\", \"cloramical\", \"cloramicol\", \"cloramidina\", \"cloranfenicol\", \"cloroamfenicolo\", \"clorocyn\", \"cloromisan\", \"cloromissan\", \"clorosintex\",
\"comycetin\", \"cylphenicol\", \"desphen\", \"detreomycin\", \"detreomycine\", \"dextromycetin\", \"doctamicina\", \"duphenicol\", \"econochlor\", \"embacetin\", \"emetren\", \"enicol\", \"enteromycetin\", \"erbaplast\", \"ertilen\", \"f armicetina\", \"farmicetina\", \"fenicol\", \"globenicol\", \"glorous\", \"halomycetin\", \"hortfenicol\", \"interomycetine\", \"intramycetin\", \"intramyctin\", \"isicetin\", \"ismicetina\", \"isophenicol\", \"isopto fenicol\", \"juvamycetin\", \"kamaver\", \"kemicetina\", \"kemicetine\", \"kloramfenikol\", \"klorita\", \"klorocid s\",
\"laevomycetinum\", \"leukamycin\", \"leukomyan\", \"leukomycin\", \"levocin\", \"levomicetina\", \"levomitsetin\", \"levomycetin\", \"levoplast\", \"levosin\", \"levovetin\", \"loromicetina\", \"loromisan\", \"loromisin\", \"mastiphen\", \"mediamycetine\", \"medichol\", \"micloretin\", \"micochlorine\", \"micoclorina\", \"microcetina\", \"mychel\", \"mycinol\", \"myclocin\", \"mycochlorin\", \"myscel\", \"normimycin v\", \"novochlorocap\", \"novomycetin\", \"novophenicol\", \"ocuphenicol\", \"oftalent\", \"oleomycetin\", \"opclor\", \"opelor\", \"ophthochlor\", \"ophthocort\",
\"ophtochlor\", \"optomycin\", \"otachron\", \"otophen\", \"pantovernil\", \"paraxin\", \"pentamycetin\", \"quemicetina\", \"rivomycin\", \"romphenil\", \"ronfenil\", \"ronphenil\", \"septicol\", \"sificetina\", \"sintomicetina\", \"sintomicetine r\", \"sno phenicol\", \"soluthor\", \"stanomycetin\", \"synthomycetin\", \"synthomycetine\", \"synthomycine\", \"syntomycin\", \"tevcocin\", \"tevcosin\", \"tifomycin\", \"tifomycine\", \"tiromycetin\", \"treomicetina\", \"unimycetin\", \"veticol\", \"vice ton\", \"viceton\")" 3 "g" 3 "g" "c(\"15101-9\", \"16603-3\", \"16604-1\", \"25247-8\", \"29214-4\", \"29346-4\", \"29347-2\", \"3455-3\")"
"CTE" 54675777 "Chlortetracycline" "Tetracyclines" "c(\"A01AB21\", \"D06AA02\", \"J01AA03\", \"S01AA02\")" "Tetracyclines" "Tetracyclines" "" "c(\"acronize\", \"aueromycin\", \"aureocina\", \"aureomycin\", \"aureomykoin\", \"biomitsin\", \"biomycin\", \"biomycin a\", \"chlormax\", \"chlorotetracycline\", \"chlortetracycline\", \"chlortetracyclinum\", \"chrysomykine\", \"clortetraciclina\", \"duomycin\", \"flamycin\", \"uromycin\")" 1 "g" "87600-3"
"CIC" 19003 "Ciclacillin" "Beta-lactams/penicillins" "" "c(\"bastcillin\", \"calthor\", \"ciclacilina\", \"ciclacillin\", \"ciclacilline\", \"ciclacillinum\", \"ciclacillum\", \"citosarin\", \"cyclacillin\", \"cyclapen\", \"noblicil\", \"orfilina\", \"peamezin\", \"syngacillin\", \"ultracillin\", \"vastcillin\", \"vipicil\", \"wyvital\")" "character(0)"
"CIX" 47472 "Ciclopirox" "Antifungals/antimycotics" "c(\"D01AE14\", \"G01AX12\")" "Antifungals for topical use" "Other antifungals for topical use" "cipx" "c(\"butaconazole\", \"butoconazol\", \"butoconazole\", \"butoconazolum\", \"compositenstarke\", \"dahlin\", \"femstat\", \"gynofort\", \"polyfructosanum\")" "character(0)"
"CIN" 2762 "Cinoxacin" "Quinolones" "J01MB06" "Quinolone antibacterials" "Other quinolones" "c(\"cino\", \"cnox\")" "c(\"azolinic acid\", \"cinobac\", \"cinobactin\", \"cinoxacin\", \"cinoxacine\", \"cinoxacino\", \"cinoxacinum\", \"clinoxacin\", \"noxigram\", \"uronorm\")" 1 "g" "character(0)"
"CIP" 2764 "Ciprofloxacin" "Quinolones" "c(\"J01MA02\", \"S01AE03\", \"S02AA15\", \"S03AA07\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"ci\", \"cip\", \"cipr\", \"cp\")" "c(\"alcon cilox\", \"auripro\", \"bacquinor\", \"baflox\", \"baycip\", \"bernoflox\", \"cetraxal\", \"ciflox\", \"cifloxin\", \"ciloxan\", \"ciplus\", \"ciprecu\", \"ciprine\", \"ciprinol\", \"cipro i.v.\", \"cipro iv\", \"cipro xl\", \"cipro xr\", \"ciprobay\", \"ciprobay uro\", \"ciprocinol\", \"ciprodar\", \"ciproflox\", \"ciprofloxacin\", \"ciprofloxacina\", \"ciprofloxacine\", \"ciprofloxacino\", \"ciprofloxacinum\", \"ciprogis\", \"ciprolin\", \"ciprolon\", \"cipromycin\", \"ciproquinol\", \"ciprowin\", \"ciproxan\", \"ciproxin\", \"ciproxina\", \"ciproxine\", \"ciriax\",
\"citopcin\", \"corsacin\", \"cyprobay\", \"fimoflox\", \"flociprin\", \"ipiflox\", \"italnik\", \"linhaliq\", \"otiprio\", \"probiox\", \"proflaxin\", \"quinolid\", \"quintor\", \"rancif\", \"roxytal\", \"septicide\", \"sophixin ofteno\", \"spitacin\", \"superocin\", \"velmonit\", \"velomonit\", \"zumaflox\")" 1 "g" 0.8 "g" "c(\"14031-9\", \"14032-7\", \"14058-2\", \"14059-0\", \"25248-6\", \"34636-1\", \"3484-3\")"
"CLR" 84029 "Clarithromycin" "Macrolides/lincosamides" "J01FA09" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"ch\", \"cla\", \"clar\", \"clm\", \"clr\")" "c(\"abbotic\", \"astromen\", \"biaxin\", \"biaxin filmtab\", \"biaxin hp\", \"biaxin xl\", \"biaxin xl filmtab\", \"bicrolid\", \"clacee\", \"clacid\", \"clacine\", \"clambiotic\", \"clarem\", \"claribid\", \"claricide\", \"claridar\", \"claripen\", \"clarith\", \"clarithromycin\", \"clarithromycine\", \"clarithromycinum\", \"claritromicina\", \"clathromycin\", \"crixan\", \"cyllid\", \"cyllind\", \"fromilid\", \"heliclar\", \"klabax\", \"klacid\", \"klaciped\", \"klaricid\", \"klaricid h.p\", \"klaricid h.p.\", \"klaricid pediatric\", \"klaricid xl\", \"klarid\", \"klarin\",
\"kofron\", \"mabicrol\", \"macladin\", \"maclar\", \"veclam\", \"vikrol\", \"zeclar\")" 0.5 "g" 1 "g" "c(\"16619-9\", \"25253-6\", \"34638-7\", \"80559-8\")"
"CLA1" 5280980 "Clavulanic acid" "Other antibacterials" "" "c(\"acide clavulanique\", \"acido clavulanico\", \"acidum clavulanicum\", \"clavulanate\", \"clavulanate acid\", \"clavulanate lithium\", \"clavulanic acid\", \"clavulansaeure\", \"clavulansaure\", \"clavulinic acid\", \"clavulox\", \"sodium clavulanate\")" "character(0)"
"CLX" 60063 "Clinafloxacin" "Quinolones" "" "clinafloxacin" "character(0)"
"CLI" 446598 "Clindamycin" "Macrolides/lincosamides" "c(\"D10AF01\", \"G01AA10\", \"J01FF01\")" "Macrolides, lincosamides and streptogramins" "Lincosamides" "c(\"cc\", \"cd\", \"cli\", \"clin\", \"cm\", \"da\")" "c(\"antirobe\", \"chlolincocin\", \"clindaderm\", \"clindamicina\", \"clindamycin\", \"clindamycine\", \"clindamycinum\", \"clinimycin\", \"dalacin c\", \"dalacine\", \"klimicin\", \"sobelin\")" 1.2 "g" 1.8 "g" "c(\"16621-5\", \"16622-3\", \"25249-4\", \"3486-8\")"
"CLF" 2794 "Clofazimine" "Antimycobacterials" "J04BA01" "Drugs for treatment of lepra" "Drugs for treatment of lepra" "clof" "c(\"chlofazimine\", \"clofazimin\", \"clofazimina\", \"clofazimine\", \"clofaziminum\", \"lampren\", \"lamprene\", \"riminophenazine\")" 0.1 "g" "character(0)"
"CLF1" 2799 "Clofoctol" "Other antibacterials" "J01XX03" "Other antibacterials" "Other antibacterials" "" "c(\"clofoctol\", \"clofoctolo\", \"clofoctolum\", \"gramplus\", \"octofene\")" "character(0)"
"CLM" 71807 "Clometocillin" "Beta-lactams/penicillins" "J01CE07" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"chlomethocillin\", \"clometacillin\", \"clometocilina\", \"clometocillin\", \"clometocilline\", \"clometocillinum\", \"rixapen\")" 1 "g" "character(0)"
"CLM1" 54680675 "Clomocycline" "Tetracyclines" "J01AA11" "Tetracyclines" "Tetracyclines" "" "c(\"chlormethylencycline\", \"clomociclina\", \"clomocyclin\", \"clomocycline\", \"clomocyclinum\", \"megaclor\")" 1 "g" "character(0)"
"CTR" 2812 "Clotrimazole" "Antifungals/antimycotics" "c(\"A01AB18\", \"D01AC01\", \"G01AF02\")" "clot" "c(\"canesten\", \"canesten cream\", \"canesten solution\", \"canestene\", \"canestine\", \"canifug\", \"chlotrimazole\", \"cimitidine\", \"clomatin\", \"clotrimaderm\", \"clotrimaderm cream\", \"clotrimazol\", \"clotrimazole\", \"clotrimazolum\", \"cutistad\", \"desamix f\", \"diphenylmethane\", \"empecid\", \"esparol\", \"fem care\", \"femcare\", \"gyne lotrimin\", \"jidesheng\", \"kanesten\", \"klotrimazole\", \"lotrimax\", \"lotrimin\", \"lotrimin af\", \"lotrimin af cream\", \"lotrimin af lotion\", \"lotrimin af solution\", \"lotrimin cream\", \"lotrimin lotion\",
\"lotrimin solution\", \"monobaycuten\", \"mycelax\", \"mycelex\", \"mycelex cream\", \"mycelex g\", \"mycelex otc\", \"mycelex solution\", \"mycelex troches\", \"mycelex twin pack\", \"myclo cream\", \"myclo solution\", \"myclo spray solution\", \"mycofug\", \"mycosporin\", \"mykosporin\", \"nalbix\", \"otomax\", \"pedisafe\", \"rimazole\", \"stiemazol\", \"tibatin\", \"trimysten\", \"veltrim\")" "character(0)"
"CLO" 6098 "Cloxacillin" "Beta-lactams/penicillins" "J01CF02" "Beta-lactam antibacterials, penicillins" "Beta-lactamase resistant penicillins" "c(\"\", \"clox\")" "c(\"chloroxacillin\", \"clossacillina\", \"cloxacilina\", \"cloxacillin\", \"cloxacillin sodium\", \"cloxacilline\", \"cloxacillinna\", \"cloxacillinum\", \"cloxapen\", \"methocillin s\", \"orbenin\", \"syntarpen\", \"tegopen\")" 2 "g" 2 "g" "c(\"16628-0\", \"25250-2\")"
"COL" 5311054 "Colistin" "Polymyxins" "c(\"A07AA10\", \"J01XB01\")" "Other antibacterials" "Polymyxins" "c(\"cl\", \"coli\", \"cs\", \"cst\", \"ct\")" "c(\"belcomycine\", \"colimycin\", \"colimycin sulphate\", \"colisticin\", \"colistimethate\", \"colistimethate sodium\", \"colistin sulfate\", \"colistin sulphate\", \"colomycin\", \"coly-mycin\", \"polymyxin e\", \"polymyxin e. sulfate\", \"promixin\", \"totazina\")" 9 "MU" 9 "MU" "c(\"16645-4\", \"29493-4\")"
"COP" "Colistin/polysorbate" "Other antibacterials" "" "" ""
"CYC" 6234 "Cycloserine" "Oxazolidinones" "J04AB01" "Drugs for treatment of tuberculosis" "Antibiotics" "cycl" "c(\"cicloserina\", \"closerin\", \"closina\", \"cyclorin\", \"cycloserin\", \"cycloserine\", \"cycloserinum\", \"farmiserina\", \"micoserina\", \"miroserina\", \"miroseryn\", \"novoserin\", \"oxamicina\", \"oxamycin\", \"seromycin\", \"tebemicina\", \"tisomycin\", \"wasserina\")" 0.75 "g" "c(\"16702-3\", \"25251-0\", \"3519-6\")"
"DAL" 23724878 "Dalbavancin" "Glycopeptides" "J01XA04" "Other antibacterials" "Glycopeptide antibacterials" "dalb" "c(\"dalbavancin\", \"dalvance\")" 1.5 "g" "character(0)"
"DAN" 71335 "Danofloxacin" "Quinolones" "" "c(\"advocin\", \"danofloxacin\", \"danofloxacine\", \"danofloxacino\", \"danofloxacinum\")" "character(0)"
"DPS" 2955 "Dapsone" "Other antibacterials" "c(\"D10AX05\", \"J04BA02\")" "Drugs for treatment of lepra" "Drugs for treatment of lepra" "" "c(\"aczone\", \"araldite ht\", \"atrisone\", \"avlosulfon\", \"avlosulfone\", \"avlosulphone\", \"avsulfor\", \"bis sulfone\", \"bissulfone\", \"bissulphone\", \"croysulfone\", \"croysulphone\", \"dapson\", \"dapsona\", \"dapsone\", \"dapsonum\", \"di sulfone\", \"diaphenyl sulfone\", \"diaphenylsulfon\", \"diaphenylsulfone\", \"diaphenylsulphon\", \"diaphenylsulphone\", \"dimitone\", \"diphenasone\", \"diphone\", \"disulfone\", \"disulone\", \"disulphone\", \"dubronax\", \"dubronaz\", \"dumitone\", \"eporal\", \"metabolite c\", \"novophone\", \"protogen\", \"servidapson\",
\"slphadione\", \"sulfadione\", \"sulfona\", \"sulfone ucb\", \"sulfonyldianiline\", \"sulphadione\", \"sulphonyldianiline\", \"sumicure s\", \"tarimyl\", \"udolac\", \"wln: zr dswr dz\")" 50 "mg" "9747-7"
"DAP" 16134395 "Daptomycin" "Other antibacterials" "J01XX09" "Other antibacterials" "Other antibacterials" "c(\"dap\", \"dapt\")" "c(\"cidecin\", \"cubicin\", \"dapcin\", \"daptomicina\", \"daptomycine\", \"daptomycinum\")" 0.28 "g" "character(0)"
"DFX" 487101 "Delafloxacin" "Quinolones" "J01MA23" "" "c(\"baxdela\", \"delafloxacin\", \"delafloxacinum\")" 0.9 "g" 0.6 "g" "character(0)"
"DLM" 6480466 "Delamanid" "Antimycobacterials" "J04AK06" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "dela" "c(\"delamanid\", \"deltyba\")" 0.2 "g" "character(0)"
"DEM" 54680690 "Demeclocycline" "Tetracyclines" "c(\"D06AA01\", \"J01AA01\")" "Tetracyclines" "Tetracyclines" "" "c(\"bioterciclin\", \"clortetrin\", \"deganol\", \"demeclociclina\", \"demeclocycline\", \"demeclocyclinum\", \"demeclor\", \"demetraclin\", \"diuciclin\", \"elkamicina\", \"ledermycin\", \"mexocine\", \"novotriclina\", \"perciclina\", \"sumaclina\")" 0.6 "g" "c(\"10982-7\", \"29494-2\")"
"DKB" 470999 "Dibekacin" "Aminoglycosides" "J01GB09" "Aminoglycoside antibacterials" "Other aminoglycosides" "" "c(\"debecacin\", \"dibekacin\", \"dibekacin sulfate\", \"dibekacina\", \"dibekacine\", \"dibekacinum\", \"dideoxykanamycin b\", \"kappati\", \"orbicin\", \"panamicin\")" 0.14 "g" "character(0)"
"DIC" 18381 "Dicloxacillin" "Beta-lactams/penicillins" "J01CF01" "Beta-lactam antibacterials, penicillins" "Beta-lactamase resistant penicillins" "c(\"\", \"dicl\")" "c(\"dichloroxacillin\", \"diclossacillina\", \"dicloxaciclin\", \"dicloxacilin\", \"dicloxacilina\", \"dicloxacillin\", \"dicloxacillin sodium\", \"dicloxacillina\", \"dicloxacilline\", \"dicloxacillinum\", \"dicloxacycline\", \"dycill\", \"dynapen\", \"maclicine\", \"nm|| dicloxacillin\", \"pathocil\")" 2 "g" 2 "g" "c(\"10984-3\", \"16769-2\", \"25252-8\")"
"DIF" 56206 "Difloxacin" "Quinolones" "" "difloxacin" "character(0)"
"DIR" 6473883 "Dirithromycin" "Macrolides/lincosamides" "J01FA13" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"dirithromycin\", \"dirithromycine\", \"dirithromycinum\", \"diritromicina\", \"divitross\", \"dynabac\", \"noriclan\", \"valodin\")" 0.5 "g" "character(0)"
"DOR" 73303 "Doripenem" "Carbapenems" "J01DH04" "Other beta-lactam antibacterials" "Carbapenems" "dori" "c(\"doribax\", \"doripenem\", \"doripenem hydrate\", \"finibax\")" 1.5 "g" "character(0)"
"DOX" 54671203 "Doxycycline" "Tetracyclines" "c(\"A01AB22\", \"J01AA02\")" "Tetracyclines" "Tetracyclines" "c(\"dox\", \"doxy\")" "c(\"atridox\", \"azudoxat\", \"deoxymykoin\", \"dossiciclina\", \"doxcycline anhydrous\", \"doxiciclina\", \"doxitard\", \"doxivetin\", \"doxycen\", \"doxychel\", \"doxycin\", \"doxycyclin\", \"doxycycline\", \"doxycycline calcium\", \"doxycycline hyclate\", \"doxycyclinum\", \"doxylin\", \"doxysol\", \"doxytec\", \"doxytetracycline\", \"hydramycin\", \"investin\", \"jenacyclin\", \"liviatin\", \"monodox\", \"oracea\", \"periostat\", \"ronaxan\", \"spanor\", \"supracyclin\", \"vibramycin\", \"vibramycin novum\", \"vibramycine\", \"vibravenos\", \"zenavod\")" 0.1 "g" 0.1 "g" "c(\"10986-8\", \"21250-6\", \"26902-7\")"
"ECO" 3198 "Econazole" "Antifungals/antimycotics" "c(\"D01AC03\", \"G01AF05\")" "Antifungals for topical use" "Imidazole and triazole derivatives" "econ" "c(\"econazol\", \"econazole\", \"econazolum\", \"ecostatin\", \"ecostatin cream\", \"palavale\", \"pevaryl\", \"spectazole\", \"spectazole cream\")" "character(0)"
"ENX" 3229 "Enoxacin" "Quinolones" "J01MA04" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"enox\")" "c(\"almitil\", \"bactidan\", \"bactidron\", \"comprecin\", \"enofloxacine\", \"enoksetin\", \"enoram\", \"enoxacin\", \"enoxacina\", \"enoxacine\", \"enoxacino\", \"enoxacinum\", \"enoxen\", \"enoxin\", \"enoxor\", \"flumark\", \"penetrex\")" 0.8 "g" "c(\"16816-1\", \"3590-7\")"
"ENR" 71188 "Enrofloxacin" "Quinolones" "" "c(\"baytril\", \"enrofloxacin\", \"enrofloxacine\", \"enrofloxacino\", \"enrofloxacinum\")" "character(0)"
"ENV" 135565326 "Enviomycin" "Antimycobacterials" "c(\"\", \"tuberactinomycin\")" "c(\"enviomicina\", \"enviomycin\", \"enviomycina\", \"enviomycinum\")" "character(0)"
"EPE" "Eperozolid" "Other antibacterials" "" "" ""
"EPC" 71392 "Epicillin" "Beta-lactams/penicillins" "J01CA07" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"dexacillin\", \"dihydroampicillin\", \"epicilina\", \"epicillin\", \"epicilline\", \"epicillinum\")" 2 "g" 2 "g" "character(0)"
"EPP" 68916 "Epiroprim" "Other antibacterials" "" "c(\"epiroprim\", \"epiroprima\", \"epiroprime\", \"epiroprimum\")" "character(0)"
"ERV" 54726192 "Eravacycline" "Tetracyclines" "J01AA13" "Tetracyclines" "Tetracyclines" "erav" "eravacycline" "character(0)"
"ETP" 150610 "Ertapenem" "Carbapenems" "J01DH03" "Other beta-lactam antibacterials" "Carbapenems" "c(\"erta\", \"etp\")" "c(\"ertapenem\", \"invanz\")" 1 "g" "character(0)"
"ERY" 12560 "Erythromycin" "Macrolides/lincosamides" "c(\"D10AF02\", \"J01FA01\", \"S01AA17\")" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"e\", \"em\", \"ery\", \"eryt\")" "c(\"abboticin\", \"abomacetin\", \"acneryne\", \"acnesol\", \"akne cordes losung\", \"aknederm ery gel\", \"aknemycin\", \"austrias\", \"benzamycin\", \"derimer\", \"deripil\", \"dotycin\", \"dumotrycin\", \"emuvin\", \"emycin\", \"endoeritrin\", \"erecin\", \"erisone\", \"eritomicina\", \"eritrocina\", \"eritromicina\", \"ermycin\", \"eryacne\", \"eryacnen\", \"eryc sprinkles\", \"erycen\", \"erycette\", \"erycin\", \"erycinum\", \"eryderm\", \"erydermer\", \"erygel\", \"eryhexal\", \"erymax\", \"erymed\", \"erysafe\", \"erytab\", \"erythrocin\", \"erythrocin stearate\",
\"erythroderm\", \"erythrogran\", \"erythroguent\", \"erythromid\", \"erythromycin\", \"erythromycin a\", \"erythromycin base\", \"erythromycin lactate\", \"erythromycine\", \"erythromycines\", \"erythromycinum\", \"erytop\", \"erytrociclin\", \"ilocaps\", \"ilosone\", \"iloticina\", \"ilotycin\", \"ilotycin gluceptate\", \"ilotycin t.s.\", \"inderm\", \"inderm gel\", \"indermretcin\", \"latotryd\", \"lederpax\", \"mephamycin\", \"mercina\", \"oftamolets\", \"paediathrocin\", \"pantoderm\", \"pantodrin\", \"pantomicina\", \"pce dispertab\", \"pharyngocin\", \"primacine\",
\"propiocine\", \"proterytrin\", \"retcin\", \"robimycin\", \"romycin\", \"sansac\", \"skid gel e\", \"staticin\", \"stiemicyn\", \"stiemycin\", \"theramycin z\", \"tiloryth\", \"tiprocin\", \"torlamicina\", \"udima ery gel\", \"wyamycin s\")" 2 "g" 1 "g" "c(\"12298-6\", \"16829-4\", \"25275-9\", \"3597-2\")"
"ETH" 14052 "Ethambutol" "Antimycobacterials" "J04AK02" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "etha" "c(\"aethambutolum\", \"ebutol\", \"etambutol\", \"etambutolo\", \"etapiam\", \"ethambutol\", \"ethambutolum\", \"myambutol\", \"mycobutol\", \"purderal\", \"servambutol\")" 1.2 "g" 1.2 "g" "c(\"25404-5\", \"3607-9\")"
"ETI" 456476 "Ethambutol/isoniazid" "Antimycobacterials" "J04AM03" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""
"ETI1" 2761171 "Ethionamide" "Antimycobacterials" "J04AD03" "Drugs for treatment of tuberculosis" "Thiocarbamide derivatives" "ethi" "c(\"aethionamidum\", \"aetina\", \"aetiva\", \"amidazin\", \"amidazine\", \"ethatyl\", \"ethimide\", \"ethina\", \"ethinamide\", \"ethionamide\", \"ethionamidum\", \"ethioniamide\", \"ethylisothiamide\", \"ethyonomide\", \"etimid\", \"etiocidan\", \"etionamid\", \"etionamida\", \"etionamide\", \"etioniamid\", \"etionid\", \"etionizin\", \"etionizina\", \"etionizine\", \"fatoliamid\", \"iridocin\", \"iridocin bayer\", \"iridozin\", \"isothin\", \"isotiamida\", \"itiocide\", \"nicotion\", \"nisotin\", \"nizotin\", \"rigenicid\", \"sertinon\", \"teberus\", \"thianid\", \"thianide\",
\"thioamide\", \"thiodine\", \"thiomid\", \"thioniden\", \"tianid\", \"tiomid\", \"trecator\", \"trecator sc\", \"trekator\", \"trescatyl\", \"trescazide\", \"tubenamide\", \"tubermin\", \"tuberoid\", \"tuberoson\")" 0.75 "g" "16845-0"
"ETO" 6034 "Ethopabate" "Other antibacterials" "" "c(\"amprol plus\", \"ethopabat\", \"ethopabate\", \"ethyl pabate\")" "character(0)"
"EXE" "Exebacase" "" "" ""
"FAR" 65894 "Faropenem" "Other antibacterials" "J01DI03" "Other beta-lactam antibacterials" "Other cephalosporins and penems" "" "c(\"faropenem\", \"faropenem sodium\", \"fropenem\", \"fropenum sodium\")" 0.75 "g" "character(0)"
"FDX" 10034073 "Fidaxomicin" "Other antibacterials" "A07AA12" "" "c(\"dificid\", \"dificlir\", \"difimicin\", \"fidaxomicin\", \"lipiarmycin\", \"tiacumicin b\")" 0.4 "g" "character(0)"
"FIN" 11567473 "Finafloxacin" "Quinolones" "" "finafloxacin" "character(0)"
"FLA" 46783781 "Flavomycin" "Other antibacterials" "" "moenomycin complex" "character(0)"
"FLE" 3357 "Fleroxacin" "Quinolones" "J01MA08" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"fler\")" "c(\"fleroxacin\", \"fleroxacine\", \"fleroxacino\", \"fleroxacinum\", \"fleroxicin\", \"megalocin\", \"megalone\", \"megalosin\", \"quinodis\")" 0.4 "g" 0.4 "g" "character(0)"
"FLO" 65864 "Flomoxef" "Other antibacterials" "J01DC14" "" "c(\"flomoxef\", \"flomoxefo\", \"flomoxefum\")" 2 "g" "character(0)"
"FLR" 114811 "Florfenicol" "Other antibacterials" "" "c(\"aquafen\", \"florfenicol\", \"nuflor\", \"nuflor gold\")" "87599-7"
"FLC" 21319 "Flucloxacillin" "Beta-lactams/penicillins" "J01CF05" "Beta-lactam antibacterials, penicillins" "Beta-lactamase resistant penicillins" "c(\"clox\", \"flux\")" "c(\"floxacillin\", \"floxapen\", \"floxapen sodium salt\", \"fluclox\", \"flucloxacilina\", \"flucloxacillin\", \"flucloxacilline\", \"flucloxacillinum\", \"fluorochloroxacillin\")" 2 "g" 2 "g" "character(0)"
"FLU" 3365 "Fluconazole" "Antifungals/antimycotics" "c(\"D01AC15\", \"J02AC01\")" "Antimycotics for systemic use" "Triazole derivatives" "c(\"fluc\", \"fluz\", \"flz\")" "c(\"alflucoz\", \"alfumet\", \"biocanol\", \"biozole\", \"biozolene\", \"canzol\", \"cryptal\", \"diflazon\", \"diflucan\", \"dimycon\", \"elazor\", \"flucazol\", \"fluconazol\", \"fluconazole\", \"fluconazole capsules\", \"fluconazolum\", \"flucostat\", \"flukezol\", \"flunazol\", \"flunizol\", \"flusol\", \"fluzon\", \"fluzone\", \"forcan\", \"fuconal\", \"fungata\", \"loitin\", \"oxifugol\", \"pritenzol\", \"syscan\", \"trican\", \"triconal\", \"triflucan\", \"zoltec\")" 0.2 "g" 0.2 "g" "c(\"10987-6\", \"16870-8\", \"25255-1\", \"80530-9\")"
"FLM" 3374 "Flumequine" "Quinolones" "J01MB07" "Quinolone antibacterials" "Other quinolones" "" "c(\"apurone\", \"fantacin\", \"flumequine\", \"flumequino\", \"flumequinum\", \"flumigal\", \"flumiquil\", \"flumisol\", \"flumix\", \"imequyl\")" 1.2 "g" "character(0)"
"FLR1" 71260 "Flurithromycin" "Macrolides/lincosamides" "J01FA14" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"flurithromicina\", \"flurithromycime\", \"flurithromycin\", \"flurithromycine\", \"flurithromycinum\", \"fluritromicina\", \"fluritromycinum\", \"flurizic\")" 0.75 "g" "character(0)"
"FFL" 214356 "Fosfluconazole" "Antifungals/antimycotics" "" "c(\"fosfluconazole\", \"phosfluconazole\", \"procif\", \"prodif\")" "character(0)"
"FOS" 446987 "Fosfomycin" "Other antibacterials" "J01XX01" "Other antibacterials" "Other antibacterials" "c(\"ff\", \"fm\", \"fo\", \"fof\", \"fos\", \"fosf\")" "c(\"fosfocina\", \"fosfomicina\", \"fosfomycin\", \"fosfomycin sodium\", \"fosfomycine\", \"fosfomycinum\", \"fosfonomycin\", \"monuril\", \"monurol\", \"phosphonemycin\", \"phosphonomycin\", \"veramina\")" 3 "g" 8 "g" "character(0)"
"FMD" 572 "Fosmidomycin" "Other antibacterials" "" "c(\"fosmidomycin\", \"fosmidomycina\", \"fosmidomycine\", \"fosmidomycinum\")" "character(0)"
"FRM" 8378 "Framycetin" "Aminoglycosides" "c(\"D09AA01\", \"R01AX08\", \"S01AA07\")" "c(\"\", \"fram\")" "c(\"actilin\", \"actiline\", \"antibiotique\", \"bycomycin\", \"endomixin\", \"enterfram\", \"fradiomycin\", \"fradiomycin b\", \"fradiomycinum\", \"framicetina\", \"framycetin\", \"framycetin sulfate\", \"framycetine\", \"framycetinum\", \"framygen\", \"fraquinol\", \"jernadex\", \"myacine\", \"myacyne\", \"mycerin\", \"mycifradin\", \"neobrettin\", \"neolate\", \"neomas\", \"neomcin\", \"neomicina\", \"neomin\", \"neomycin\", \"neomycin b\", \"neomycin b sulfate\", \"neomycin solution\", \"neomycin sulfate\", \"neomycin sulphate\", \"neomycinb\", \"neomycine\", \"neomycinum\",
\"nivemycin\", \"pimavecort\", \"soframycin\", \"soframycine\", \"tuttomycin\", \"vonamycin\", \"vonamycin powder v\")" "character(0)"
"FRZ" 5323714 "Furazolidone" "Other antibacterials" "G01AX06" "" "c(\"bifuron\", \"corizium\", \"coryzium\", \"diafuron\", \"enterotoxon\", \"furall\", \"furaxon\", \"furaxone\", \"furazol\", \"furazolidine\", \"furazolidon\", \"furazolidona\", \"furazolidone\", \"furazolidonum\", \"furazolum\", \"furazon\", \"furidon\", \"furovag\", \"furox aerosol powder\", \"furoxal\", \"furoxane\", \"furoxon\", \"furoxone\", \"furoxone liquid\", \"furoxone swine mix\", \"furozolidine\", \"giardil\", \"giarlam\", \"medaron\", \"neftin\", \"nicolen\", \"nifulidone\", \"nifuran\", \"nifurazolidone\", \"nifurazolidonum\", \"nitrofurazolidone\", \"nitrofurazolidonum\",
\"nitrofuroxon\", \"optazol\", \"ortazol\", \"puradin\", \"roptazol\", \"sclaventerol\", \"tikofuran\", \"topazone\", \"trichofuron\", \"tricofuron\", \"tricoron\", \"trifurox\", \"viofuragyn\")" "character(0)"
"FUS" 3000226 "Fusidic acid" "Other antibacterials" "c(\"D06AX01\", \"D09AA02\", \"J01XC01\", \"S01AA13\")" "Other antibacterials" "Steroid antibacterials" "c(\"fa\", \"fusi\")" "c(\"acide fusidique\", \"acido fusidico\", \"acidum fusidicum\", \"flucidin\", \"fucidate\", \"fucidate sodium\", \"fucidic acid\", \"fucidin\", \"fucidin acid\", \"fucithalmic\", \"fusidate\", \"fusidate acid\", \"fusidic acid\", \"fusidine\", \"fusidinic acid\", \"ramycin\")" 1.5 "g" 1.5 "g" "character(0)"
"GAM" 59364992 "Gamithromycin" "Macrolides/lincosamides" "" "gamithromycin" "character(0)"
"GRN" 124093 "Garenoxacin" "Quinolones" "J01MA19" "" "c(\"ganefloxacin\", \"garenfloxacin\", \"garenoxacin\")" 0.4 "g" "character(0)"
"GAT" 5379 "Gatifloxacin" "Quinolones" "c(\"J01MA16\", \"S01AE06\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"gati\")" "c(\"gatiflo\", \"gatifloxacin\", \"gatifloxacine\", \"gatifloxcin\", \"gatilox\", \"gatiquin\", \"gatispan\", \"tequin\", \"tequin and zymar\", \"zymaxid\")" 0.4 "g" 0.4 "g" "character(0)"
"GEM" 9571107 "Gemifloxacin" "Quinolones" "J01MA15" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"factiv\", \"factive\", \"gemifioxacin\", \"gemifloxacin\", \"gemifloxacine\", \"gemifloxacino\", \"gemifloxacinum\")" 0.32 "g" "character(0)"
"GEN" 3467 "Gentamicin" "Aminoglycosides" "c(\"D06AX07\", \"J01GB03\", \"S01AA11\", \"S02AA14\", \"S03AA06\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "c(\"cn\", \"gen\", \"gent\", \"gm\")" "c(\"apogen\", \"centicin\", \"cidomycin\", \"garasol\", \"genoptic liquifilm\", \"genoptic s.o.p.\", \"gentacycol\", \"gentafair\", \"gentak\", \"gentamar\", \"gentamcin sulfate\", \"gentamicin\", \"gentamicina\", \"gentamicine\", \"gentamicins\", \"gentamicinum\", \"gentamycin\", \"gentamycins\", \"gentamycinum\", \"gentavet\", \"gentocin\", \"jenamicin\", \"lyramycin\", \"oksitselanim\", \"refobacin\", \"refobacin tm\", \"septigen\", \"uromycine\")" 0.24 "g" "c(\"13561-6\", \"13562-4\", \"15106-8\", \"22746-2\", \"22747-0\", \"31091-2\", \"31092-0\", \"31093-8\", \"35668-3\", \"3663-2\", \"3664-0\", \"3665-7\", \"39082-3\", \"47109-4\", \"59379-8\", \"80971-5\", \"88111-0\")"
"GEH" "Gentamicin-high" "Aminoglycosides" "c(\"gehi\", \"gehl\", \"genta high\", \"gentamicin high\")" "" ""
"GEP" 25101874 "Gepotidacin" "Other antibacterials" "" "gepotidacin" "character(0)"
"GRX" 72474 "Grepafloxacin" "Quinolones" "J01MA11" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"grep\")" "grepafloxacin" 0.4 "g" "character(0)"
"GRI" 441140 "Griseofulvin" "Antifungals/antimycotics" "c(\"D01AA08\", \"D01BA01\")" "" "c(\"amudane\", \"curling factor\", \"delmofulvina\", \"fulcin\", \"fulcine\", \"fulvican grisactin\", \"fulvicin\", \"fulvicin bolus\", \"fulvidex\", \"fulvina\", \"fulvinil\", \"fulvistatin\", \"fungivin\", \"greosin\", \"gresfeed\", \"gricin\", \"grifulin\", \"grifulvin\", \"grifulvin v\", \"grisactin\", \"grisactin ultra\", \"grisactin v\", \"griscofulvin\", \"grise ostatin\", \"grisefuline\", \"griseo\", \"griseofulvin\", \"griseofulvin forte\", \"griseofulvina\", \"griseofulvine\", \"griseofulvinum\", \"griseomix\", \"griseostatin\", \"grisetin\", \"grisofulvin\",
\"grisovin\", \"grisovin fp\", \"grizeofulvin\", \"grysio\", \"guservin\", \"lamoryl\", \"likuden\", \"likunden\", \"murfulvin\", \"poncyl\", \"spirofulvin\", \"sporostatin xan\", \"xuanjing\")" 0.5 "g" "12402-4"
"HAB" 175989 "Habekacin" "Aminoglycosides" "" "c(\"arbekacin sulfate\", \"habekacin\", \"habekacin sulfate\", \"habekacin xsulfate\")" "character(0)"
"HCH" 11979956 "Hachimycin" "Antifungals/antimycotics" "c(\"D01AA03\", \"G01AA06\", \"J02AA02\")" "Antimycotics for systemic use" "Antibiotics" "" "c(\"cabimicina\", \"hachimicina\", \"hachimycin\", \"hachimycine\", \"hachimycinum\", \"trichomycinum\", \"trichonat\")" "character(0)"
"HET" 443387 "Hetacillin" "Beta-lactams/penicillins" "J01CA18" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"etacillina\", \"hetacilina\", \"hetacillin\", \"hetacilline\", \"hetacillinum\", \"phenazacillin\", \"versapen\")" 2 "g" "character(0)"
"HYG" 56928061 "Hygromycin" "Aminoglycosides" "" "c(\"antihelmycin\", \"hydromycin b\", \"hygrovetine\")" "character(0)"
"IBX" "Ibrexafungerp" "Antifungals" "" "" ""
"ICL" 213043 "Iclaprim" "Other antibacterials" "J01EA03" "" "c(\"iclaprim\", \"mersarex\")" "character(0)"
"IPM" 104838 "Imipenem" "Carbapenems" "J01DH51" "Other beta-lactam antibacterials" "Carbapenems" "c(\"imci\", \"imi\", \"imip\", \"imp\")" "c(\"imipemide\", \"imipenem\", \"imipenem anhydrous\", \"imipenem/cilastatin\", \"imipenemum\", \"imipenen\", \"primaxin\", \"tienamycin\")" 2 "g" "c(\"17010-0\", \"25257-7\", \"27331-8\", \"3688-9\")"
"IPE" "Imipenem/EDTA" "Carbapenems" "" "" ""
"IMR" "Imipenem/relebactam" "Carbapenems" "" "" ""
"ISV" 6918485 "Isavuconazole" "Antifungals/antimycotics" "J02AC05" "c(\"\", \"isav\")" "isavuconazole" 0.2 "g" 0.2 "g" "character(0)"
"ISE" 3037209 "Isepamicin" "Aminoglycosides" "J01GB11" "Aminoglycoside antibacterials" "Other aminoglycosides" "" "c(\"isepacin\", \"isepalline\", \"isepamicin\", \"isepamicina\", \"isepamicine\", \"isepamicinum\")" 0.4 "g" "character(0)"
"ISO" 3760 "Isoconazole" "Antifungals/antimycotics" "c(\"D01AC05\", \"G01AF07\")" "Antimycotics for topic use" "Triazole derivatives" "" "c(\"isoconazol\", \"isoconazole\", \"isoconazolum\", \"travogen\")" "character(0)"
"INH" 3767 "Isoniazid" "Antimycobacterials" "J04AC01" "Drugs for treatment of tuberculosis" "Hydrazides" "inh" "c(\"abdizide\", \"andrazide\", \"anidrasona\", \"antimicina\", \"antituberkulosum\", \"armacide\", \"armazid\", \"armazide\", \"atcotibine\", \"azt + isoniazid\", \"azuren\", \"bacillin\", \"cemidon\", \"chemiazid\", \"chemidon\", \"continazine\", \"cortinazine\", \"cotinazin\", \"cotinizin\", \"defonin\", \"dibutin\", \"diforin\", \"dinacrin\", \"ditubin\", \"ebidene\", \"eralon\", \"ertuban\", \"eutizon\", \"evalon\", \"fetefu\", \"fimalene\", \"hid rasonil\", \"hidranizil\", \"hidrasonil\", \"hidrulta\", \"hidrun\", \"hycozid\", \"hydrazid\", \"hydrazide\", \"hyozid\", \"i.a.i.\",
\"idrazil\", \"inizid\", \"iscotin\", \"isidrina\", \"ismazide\", \"isobicina\", \"isocid\", \"isocidene\", \"isocotin\", \"isohydrazide\", \"isokin\", \"isolyn\", \"isonerit\", \"isonex\", \"isoniacid\", \"isoniazid\", \"isoniazid sa\", \"isoniazida\", \"isoniazide\", \"isoniazidum\", \"isonicazide\", \"isonicid\", \"isonico\", \"isonicotan\", \"isonicotil\", \"isonicotinhydrazid\", \"isonicotinohydrazide\", \"isonide\", \"isonidrin\", \"isonikazid\", \"isonilex\", \"isonin\", \"isonindon\", \"isonirit\", \"isoniton\", \"isonizida\", \"isonizide\", \"isotamine\", \"isotebe\",
\"isotebezid\", \"isotinyl\", \"isozid\", \"isozide\", \"isozyd\", \"laniazid\", \"laniozid\", \"lanizid\", \"mayambutol\", \"mybasan\", \"neoteben\", \"neoxin\", \"neumandin\", \"niadrin\", \"nicazide\", \"nicetal\", \"nicizina\", \"niconyl\", \"nicotibina\", \"nicotibine\", \"nicotisan\", \"nicozide\", \"nidaton\", \"nidrazid\", \"nikozid\", \"niplen\", \"nitadon\", \"niteban\", \"nydrazid\", \"nyscozid\", \"pelazid\", \"percin\", \"phthisen\", \"pycazide\", \"pyreazid\", \"pyricidin\", \"pyridicin\", \"pyrizidin\", \"raumanon\", \"razide\", \"retozide\", \"rifater\", \"rimicid\",
\"rimifon\", \"rimiphone\", \"rimitsid\", \"robiselin\", \"robisellin\", \"roxifen\", \"sanohidrazina\", \"sauterazid\", \"sauterzid\", \"stanozide\", \"tebecid\", \"tebenic\", \"tebexin\", \"tebilon\", \"teebaconin\", \"tekazin\", \"tibazide\", \"tibemid\", \"tibiazide\", \"tibinide\", \"tibison\", \"tibivis\", \"tibizide\", \"tibusan\", \"tisiodrazida\", \"tizide\", \"tubazid\", \"tubazide\", \"tubeco\", \"tubecotubercid\", \"tuberian\", \"tubicon\", \"tubilysin\", \"tubizid\", \"tubomel\", \"unicocyde\", \"unicozyde\", \"vazadrine\", \"vederon\", \"zidafimia\", \"zinadon\",
\"zonazide\")" 0.3 "g" 0.3 "g" "c(\"25451-6\", \"26756-7\", \"3697-0\", \"40371-7\")"
"ITR" 3793 "Itraconazole" "Antifungals/antimycotics" "J02AC02" "Antimycotics for systemic use" "Triazole derivatives" "itra" "c(\"itraconazol\", \"itraconazole\", \"itraconazolum\", \"itraconzaole\", \"itrazole\", \"oriconazole\", \"sporanox\")" 0.2 "g" 0.2 "g" "c(\"10989-2\", \"12392-7\", \"25258-5\", \"27081-9\", \"32184-4\", \"32185-1\", \"80531-7\")"
"JOS" 5282165 "Josamycin" "Macrolides/lincosamides" "J01FA07" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"josacine\", \"josamicina\", \"josamycin\", \"josamycine\", \"josamycinum\")" 2 "g" "character(0)"
"KAN" 6032 "Kanamycin" "Aminoglycosides" "c(\"A07AA08\", \"J01GB04\", \"S01AA24\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "c(\"hlk\", \"k\", \"kan\", \"kana\", \"km\")" "c(\"kanamicina\", \"kanamycin\", \"kanamycin a\", \"kanamycin base\", \"kanamycine\", \"kanamycinum\", \"kantrex\", \"kenamycin a\", \"klebcil\", \"liposomal kanamycin\")" 3 "g" 1 "g" "c(\"23889-9\", \"3698-8\", \"3699-6\", \"3700-2\", \"47395-9\")"
"KAH" "Kanamycin-high" "Aminoglycosides" "c(\"\", \"k_h\", \"kahl\")" "" ""
"KAC" "Kanamycin/cephalexin" "Aminoglycosides" "" "" ""
"KET" 456201 "Ketoconazole" "Antifungals/antimycotics" "c(\"D01AC08\", \"G01AF11\", \"H02CA03\", \"J02AB02\")" "Antimycotics for systemic use" "Imidazole derivatives" "c(\"keto\", \"ktc\")" "c(\"extina\", \"fungarest\", \"fungoral\", \"ketocanazole\", \"ketoconazol\", \"ketoconazole\", \"ketoconazolum\", \"ketoderm\", \"nizoral\", \"xolegel\")" 0.2 "g" "c(\"10990-0\", \"12393-5\", \"25259-3\", \"60091-6\", \"60092-4\")"
"KIT" "Kitasamycin" "Macrolides/lincosamides" "c(\"\", \"leucomycin\")" "" ""
"LAS" 5360807 "Lasalocid" "Other antibacterials" "" "c(\"avatec\", \"lasalocid\", \"lasalocid a\", \"lasalocide\", \"lasalocide a\", \"lasalocido\", \"lasalocidum\")" "87598-9"
"LTM" 47499 "Latamoxef" "Cephalosporins (3rd gen.)" "J01DD06" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"mox\", \"moxa\", \"moxalactam\")" "c(\"disodium moxalactam\", \"festamoxin\", \"lamoxactam\", \"latamoxef\", \"latamoxefum\", \"shiomarin\")" 4 "g" "character(0)"
"LMU" 25185057 "Lefamulin" "Other antibacterials" "J01XX12" "" "lefamulin" "character(0)"
"LEN" 65646 "Lenampicillin" "Beta-lactams/penicillins" "" "c(\"lenampicilina\", \"lenampicillin\", \"lenampicillin hcl\", \"lenampicilline\", \"lenampicillinum\")" "character(0)"
"LVX" 149096 "Levofloxacin" "Quinolones" "c(\"J01MA12\", \"S01AE05\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"le\", \"lev\", \"levo\", \"lvx\")" "c(\"aeroquin\", \"cravit\", \"cravit hydrate\", \"cravit iv\", \"cravit ophthalmic\", \"elequine\", \"floxacin\", \"floxel\", \"iquix hydrate\", \"leroxacin\", \"lesacin\", \"levaquin\", \"levaquin hydrate\", \"levo floxacin\", \"levofiexacin\", \"levofloxacin\", \"levofloxacin hydrate\", \"levofloxacine\", \"levofloxacino\", \"levofloxacinum\", \"levokacin\", \"levoxacin\", \"mosardal\", \"nofaxin\", \"oftaquix\", \"quixin\", \"reskuin\", \"tavanic\", \"unibiotic\", \"venaxan\", \"volequin\")" 0.5 "g" 0.5 "g" "c(\"21368-6\", \"30532-6\", \"30533-4\")"
"LND" 9850038 "Levonadifloxacin" "Quinolones" "J01MA24" "" "levonadifloxacin" "character(0)"
"LSP" "Linco-spectin" "Other antibacterials" "c(\"\", \"lincomycin/spectinomycin\")" "" ""
"LIN" 3000540 "Lincomycin" "Macrolides/lincosamides" "J01FF02" "Macrolides, lincosamides and streptogramins" "Lincosamides" "linc" "c(\"cillimycin\", \"jiemycin\", \"lincolcina\", \"lincolnensin\", \"lincomicina\", \"lincomycin\", \"lincomycin a\", \"lincomycine\", \"lincomycinum\")" 1.8 "g" 1.8 "g" "87597-1"
"LNZ" 441401 "Linezolid" "Oxazolidinones" "J01XX08" "Other antibacterials" "Other antibacterials" "c(\"line\", \"lnz\", \"lz\", \"lzd\")" "c(\"linezlid\", \"linezoid\", \"linezolid\", \"linezolide\", \"linezolidum\", \"zivoxid\", \"zyvoxa\", \"zyvoxam\", \"zyvoxid\")" 1.2 "g" 1.2 "g" "c(\"34202-2\", \"80609-1\")"
"LFE" "Linoprist-flopristin" "Other antibacterials" "" "" ""
"LOM" 3948 "Lomefloxacin" "Quinolones" "c(\"J01MA07\", \"S01AE04\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"lmf\", \"lom\", \"lome\")" "c(\"lomefloxacin\", \"lomefloxacine\", \"lomefloxacino\", \"lomefloxacinum\", \"maxaquin\")" 0.4 "g" "character(0)"
"LOR" 5284585 "Loracarbef" "Cephalosporins (2nd gen.)" "J01DC08" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"\", \"lora\")" "c(\"anhydrous loracarbef\", \"lorabid\", \"loracarbef\", \"loracarbefum\", \"lorbef\", \"loribid\")" 0.6 "g" "character(0)"
"LYM" 54707177 "Lymecycline" "Tetracyclines" "J01AA04" "Tetracyclines" "Tetracyclines" "" "c(\"biovetin\", \"chlortetracyclin\", \"ciclisin\", \"ciclolysal\", \"infaciclina\", \"limeciclina\", \"lisinbiotic\", \"lymecyclin\", \"lymecycline\", \"lymecyclinum\", \"mucomycin\", \"ntetracycline\", \"tetralisal\", \"tetralysal\", \"vebicyclysal\")" 0.6 "g" 0.6 "g" "character(0)"
"MNA" 1292 "Mandelic acid" "Other antibacterials" "c(\"B05CA06\", \"J01XX06\")" "Other antibacterials" "Other antibacterials" "" "c(\"acido mandelico\", \"almond acid\", \"amygdalic acid\", \"benzoglycolic acid\", \"hydroxyacetic acid\", \"kyselina mandlova\", \"mandelic acid\", \"paramandelic acid\", \"phenylglycolic acid\", \"uromaline\")" 12 "g" "character(0)"
"MGX" "Manogepix" "Antifungals" "" "" ""
"MAR" 60651 "Marbofloxacin" "Quinolones" "" "c(\"marbocyl\", \"marbofloxacin\", \"marbofloxacine\", \"marbofloxacino\", \"marbofloxacinum\", \"zeniquin\")" "character(0)"
"MEC" 36273 "Mecillinam" "Beta-lactams/penicillins" "J01CA11" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"\", \"amdinocillin\")" "c(\"amdinocillin\", \"coactin\", \"hexacillin\", \"mecilinamo\", \"mecillinam\", \"mecillinamum\", \"micillinam\", \"penicillin hx\", \"selexidin\")" 1.2 "g" "character(0)"
"MEL" 71306732 "Meleumycin" "Macrolides/lincosamides" "" "" ""
"MEM" 441130 "Meropenem" "Carbapenems" "J01DH02" "Other beta-lactam antibacterials" "Carbapenems" "c(\"mem\", \"mer\", \"mero\", \"mp\", \"mrp\")" "c(\"meronem\", \"meropen\", \"meropenem\", \"meropenem anhydrous\", \"meropenem hydrate\", \"meropenem trihydrate\", \"meropenemum\", \"merrem\", \"merrem i.v.\", \"merrem iv\")" 3 "g" "41406-0"
"MNC" "Meropenem/nacubactam" "Carbapenems" "" "" ""
"MEV" "Meropenem/vaborbactam" "Carbapenems" "J01DH52" "Other beta-lactam antibacterials" "Carbapenems" "" "" 3 "g" ""
"MES" 176886 "Mesulfamide" "Other antibacterials" "" "c(\"mesulfamide\", \"mesulfamido\", \"mesulfamidum\")" "character(0)"
"MTC" 54675785 "Metacycline" "Tetracyclines" "J01AA05" "Tetracyclines" "Tetracyclines" "" "c(\"bialatan\", \"metaciclina\", \"metacycline\", \"metacyclinum\", \"methacycline\", \"methacycline base\", \"methacyclinum\", \"methylenecycline\", \"physiomycine\", \"rondomycin\")" 0.6 "g" "character(0)"
"MTM" 6713928 "Metampicillin" "Beta-lactams/penicillins" "J01CA14" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"blomopen\", \"bonopen\", \"celinmicina\", \"elatocilline\", \"fedacilina kapseln\", \"filorex\", \"italcina kapseln\", \"magnipen\", \"metabacter ampullen\", \"metambac\", \"metampicilina\", \"metampicillin\", \"metampicillin sodium\", \"metampicillina\", \"metampicilline\", \"metampicillinum\", \"methampicillin\", \"metiskia ampullen\", \"micinovo\", \"micinovo ampullen\", \"pangocilin\", \"probiotic\", \"rastomycin k\", \"relyothenate\", \"ruticina\", \"rutizina\", \"rutizina ampullen\", \"sedomycin\", \"suvipen\", \"suvipen ampullen\", \"tampilen ampullen\",
\"teonicon trofen\", \"viderpen\", \"viderpin\", \"vioplex\")" 1.5 "g" 1.5 "g" "character(0)"
"MTH" 4101 "Methenamine" "Other antibacterials" "J01XX05" "Other antibacterials" "Other antibacterials" "" "c(\"aceto hmt\", \"aminoform\", \"aminoformaldehyde\", \"ammoform\", \"ammonioformaldehyde\", \"antihydral\", \"cystamin\", \"cystex\", \"cystogen\", \"duirexol\", \"ekagom h\", \"esametilentetramina\", \"formamine\", \"formin\", \"h.m.t.\", \"heksa k\", \"herax uts\", \"heterin\", \"hexa b\", \"hexaform\", \"hexaloids\", \"hexamethylamine\", \"hexamethylenamine\", \"hexamethyleneamine\", \"hexamethylentetramin\", \"hexamine\", \"hexamine silver\", \"hexamine superfine\", \"hexaminum\", \"hexasan\", \"hexilmethylenamine\", \"metenamina\", \"metenamine\", \"methamin\",
\"methenamin\", \"methenamine\", \"methenamine silver\", \"methenaminum\", \"metramine\", \"naphthamine\", \"nocceler h\", \"preparation af\", \"resotropin\", \"sanceler h\", \"sanceler ht\", \"silver methenamine\", \"uramin\", \"uratrine\", \"urisol\", \"uritone\", \"urodeine\", \"urotropin\", \"urotropine\", \"vesaloin\", \"vesalvine\", \"xametrin\")" 3 "g" "character(0)"
"MET" 6087 "Methicillin" "Beta-lactams/penicillins" "J01CF03" "Beta-lactam antibacterials, penicillins" "Beta-lactamase resistant penicillins" "meti" "c(\"dimocillin\", \"metacillin\", \"methcilline\", \"methicillin\", \"methicillinum\", \"methycillin\", \"meticilina\", \"meticillin\", \"meticillina\", \"meticilline\", \"meticillinum\", \"staphcillin\")" 4 "g" "c(\"29492-6\", \"3788-7\")"
"MTP" 68590 "Metioprim" "Other antibacterials" "" "c(\"methioprim\", \"metioprim\", \"metioprima\", \"metioprime\", \"metioprimum\")" "character(0)"
"MXT" 3047729 "Metioxate" "Quinolones" "" "c(\"metioxate\", \"metioxato\", \"metioxatum\")" "character(0)"
"MTR" 4173 "Metronidazole" "Other antibacterials" "c(\"A01AB17\", \"D06BX01\", \"G01AF01\", \"J01XD01\", \"P01AB01\")" "Other antibacterials" "Imidazole derivatives" "c(\"metr\", \"mnz\")" "c(\"acromona\", \"anagiardil\", \"arilin\", \"atrivyl\", \"danizol\", \"deflamon\", \"efloran\", \"elyzol\", \"entizol\", \"flagemona\", \"flagesol\", \"flagil\", \"flagyl\", \"flagyl er\", \"flagyl i.v.\", \"flagyl i.v. rtu\", \"flazol\", \"flegyl\", \"florazole\", \"fossyol\", \"giatricol\", \"ginefla vir\", \"gineflavir\", \"helidac\", \"mepagyl\", \"meronidal\", \"methronidazole\", \"metric\", \"metro cream\", \"metro gel\", \"metro i.v\", \"metro i.v.\", \"metro iv\", \"metrocream\", \"metrodzhil\", \"metrogel\", \"metrogyl\", \"metrolag\", \"metrolotion\", \"metrolyl\",
\"metromidol\", \"metronidaz\", \"metronidazol\", \"metronidazole\", \"metronidazole usp\", \"metronidazolo\", \"metronidazolum\", \"metrotop\", \"metrozine\", \"metryl\", \"mexibol\", \"mexibol 'silanes'\", \"monagyl\", \"monasin\", \"nidagel\", \"nidagyl\", \"noritate\", \"novonidazol\", \"orvagil\", \"polibiotic\", \"protostat\", \"rathimed\", \"rosased\", \"sanatrichom\", \"satric\", \"takimetol\", \"trichazol\", \"trichex\", \"tricho cordes\", \"trichobrol\", \"trichocide\", \"trichomol\", \"trichopal\", \"trichopol\", \"tricocet\", \"tricom\", \"tricowas b\", \"trikacide\",
\"trikamon\", \"trikhopol\", \"trikojol\", \"trikozol\", \"trimeks\", \"trivazol\", \"vagilen\", \"vagimid\", \"vandazole\", \"vertisal\", \"wagitran\", \"zadstat\", \"zidoval\")" 2 "g" 1.5 "g" "10991-8"
"MEZ" 656511 "Mezlocillin" "Beta-lactams/penicillins" "J01CA10" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"mez\", \"mezl\", \"mz\")" "c(\"mezlin\", \"mezlocilina\", \"mezlocillin\", \"mezlocillin acid\", \"mezlocillin sodium\", \"mezlocilline\", \"mezlocillinum\", \"multocillin\")" 6 "g" "3820-8"
"MSU" "Mezlocillin/sulbactam" "Beta-lactams/penicillins" "" "" ""
"MIF" 477468 "Micafungin" "Antifungals/antimycotics" "J02AX05" "Antimycotics for systemic use" "Other antimycotics for systemic use" "c(\"\", \"mica\")" "c(\"micafungin\", \"mycamine\")" 0.1 "g" "58418-5"
"MCZ" 4189 "Miconazole" "Antifungals/antimycotics" "c(\"A01AB09\", \"A07AC01\", \"D01AC02\", \"G01AF04\", \"J02AB01\", \"S02AA13\")" "Antimycotics for systemic use" "Imidazole derivatives" "mico" "c(\"aflorix\", \"albistat\", \"andergin\", \"brentan\", \"conofite\", \"dactarin\", \"daktarin\", \"daktarin iv\", \"florid\", \"lotrimin af\", \"micantin\", \"miconasil nitrate\", \"miconazol\", \"miconazole\", \"miconazole base\", \"miconazolo\", \"miconazolum\", \"micozole\", \"minostate\", \"monista\", \"monistat\", \"monistat iv\", \"oravig\", \"vusion\", \"zimybase\", \"zimycan\")" 0.2 "g" 1 "g" "17278-3"
"MCR" 3037206 "Micronomicin" "Aminoglycosides" "S01AA22" "" "c(\"gentamicin c\", \"micromycin\", \"micronomicin\", \"micronomicina\", \"micronomicine\", \"micronomicinum\", \"sagamicin\", \"santemycin\")" "character(0)"
"MID" 5282169 "Midecamycin" "Macrolides/lincosamides" "J01FA03" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"aboren\", \"espinomycin a\", \"macropen\", \"madecacine\", \"medemycin\", \"midecamicina\", \"midecamycin\", \"midecamycin a\", \"midecamycine\", \"midecamycinum\", \"midecin\", \"momicine\", \"mydecamycin\", \"myoxam\", \"normicina\", \"rubimycin\", \"turimycin p\")" 1.2 "g" 1 "g" "character(0)"
"MIL" 37614 "Miloxacin" "Quinolones" "" "c(\"miloxacin\", \"miloxacine\", \"miloxacino\", \"miloxacinum\")" "character(0)"
"MNO" 54675783 "Minocycline" "Tetracyclines" "c(\"A01AB23\", \"D10AF07\", \"J01AA08\")" "Tetracyclines" "Tetracyclines" "c(\"mc\", \"mh\", \"mi\", \"min\", \"mino\", \"mn\", \"mno\")" "c(\"akamin\", \"aknemin\", \"borymycin\", \"dynacin\", \"klinomycin\", \"minociclina\", \"minocin\", \"minocline\", \"minocyclin\", \"minocycline\", \"minocyclinum\", \"minocyn\", \"minoderm\", \"minomycin\", \"sebomin\", \"solodyn\", \"vectrin\")" 1 "mg" 0.2 "g" "c(\"34606-4\", \"3822-4\", \"49757-8\")"
"MCM" 5282188 "Miocamycin" "Macrolides/lincosamides" "J01FA11" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"acecamycin\", \"macroral\", \"midecamycin acetate\", \"miocamen\", \"miocamycine\", \"miokamycin\", \"myocamicin\", \"ponsinomycin\")" 1.2 "g" "character(0)"
"MON" 23667299 "Monensin sodium" "Other antibacterials" "" "c(\"monensin sodium\", \"sodium monensin\")" "character(0)"
"MRN" 70374 "Morinamide" "Antimycobacterials" "J04AK04" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "" "c(\"morfazinamide\", \"morfazinammide\", \"morfgazinamide\", \"morinamida\", \"morinamide\", \"morinamidum\", \"morphazinamid\", \"morphazinamide\", \"piazofolina\", \"piazolin\", \"piazolina\")" "character(0)"
"MFX" 152946 "Moxifloxacin" "Quinolones" "c(\"J01MA14\", \"S01AE07\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"mox\", \"moxi\", \"mxf\")" "c(\"actira\", \"avelox\", \"avelox i.v.\", \"avelox iv\", \"avolex\", \"izilox\", \"moxeza\", \"moxifloxacin\", \"moxifloxacine\", \"vigamox\")" 0.4 "g" 0.4 "g" "c(\"43751-7\", \"45223-5\", \"80540-8\")"
"MUP" 446596 "Mupirocin" "Other antibacterials" "c(\"D06AX09\", \"R01AX06\")" "c(\"mup\", \"mupi\")" "c(\"bactoderm\", \"bactroban\", \"bactroban nasal\", \"bactroban ointment\", \"centany\", \"mupirocin\", \"mupirocina\", \"mupirocine\", \"mupirocinum\", \"plasimine\", \"pseudomonic acid\", \"pseudomonic acid a\", \"turixin\")" "character(0)"
"NAC" 73386748 "Nacubactam" "Beta-lactams/penicillins" "" "nacubactam" "character(0)"
"NAD" 4410 "Nadifloxacin" "Quinolones" "D10AF05" "" "c(\"acuatim\", \"nadifloxacin\", \"nadifloxacine\", \"nadifloxacino\", \"nadifloxacinum\", \"nadixa\", \"nadoxin\")" "character(0)"
"NAF" 8982 "Nafcillin" "Beta-lactams/penicillins" "J01CF06" "" "c(\"nafcilina\", \"nafcillin\", \"nafcillin sodium\", \"nafcilline\", \"nafcillinum\", \"nallpen\", \"naphcillin\", \"unipen\")" 3 "g" "c(\"10993-4\", \"25232-0\")"
"ZWK" 117587595 "Nafithromycin" "Macrolides/lincosamides" "" "nafithromycin" "character(0)"
"NAL" 4421 "Nalidixic acid" "Quinolones" "J01MB02" "Quinolone antibacterials" "Other quinolones" "c(\"na\", \"nal\", \"nali\")" "c(\"acide nalidixico\", \"acide nalidixique\", \"acido nalidissico\", \"acido nalidixico\", \"acidum nalidixicum\", \"betaxina\", \"dixiben\", \"dixinal\", \"eucisten\", \"eucistin\", \"innoxalomn\", \"innoxalon\", \"jicsron\", \"kusnarin\", \"naldixic acid\", \"nalidic acid\", \"nalidicron\", \"nalidixan\", \"nalidixane\", \"nalidixate\", \"nalidixate sodium\", \"nalidixic\", \"nalidixic acid\", \"nalidixin\", \"nalidixinic acid\", \"nalidixinsaure\", \"nalitucsan\", \"nalurin\", \"narigix\", \"naxuril\", \"neggram\", \"negram\", \"nevigramon\", \"nicelate\", \"nogram\",
\"poleon\", \"sicmylon\", \"specifen\", \"specifin\", \"unaserus\", \"uralgin\", \"uriben\", \"uriclar\", \"urisal\", \"urodixin\", \"uroman\", \"uroneg\", \"uronidix\", \"uropan\", \"wintomylon\", \"wintron\")" 4 "g" "character(0)"
"NAR" 65452 "Narasin" "Other antibacterials" "" "c(\"monteban\", \"narasin\", \"narasin a\", \"narasine\", \"narasino\", \"narasinum\", \"narasul\")" "87570-8"
"NEO" 8378 "Neomycin" "Aminoglycosides" "c(\"A01AB08\", \"A07AA01\", \"B05CA09\", \"D06AX04\", \"J01GB05\", \"R02AB01\", \"S01AA03\", \"S02AA07\", \"S03AA01\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "neom" "c(\"actilin\", \"actiline\", \"antibiotique\", \"bycomycin\", \"endomixin\", \"enterfram\", \"fradiomycin\", \"fradiomycin b\", \"fradiomycinum\", \"framicetina\", \"framycetin\", \"framycetin sulfate\", \"framycetine\", \"framycetinum\", \"framygen\", \"fraquinol\", \"jernadex\", \"myacine\", \"myacyne\", \"mycerin\", \"mycifradin\", \"neobrettin\", \"neolate\", \"neomas\", \"neomcin\", \"neomicina\", \"neomin\", \"neomycin\", \"neomycin b\", \"neomycin b sulfate\", \"neomycin solution\", \"neomycin sulfate\", \"neomycin sulphate\", \"neomycinb\", \"neomycine\", \"neomycinum\",
\"nivemycin\", \"pimavecort\", \"soframycin\", \"soframycine\", \"tuttomycin\", \"vonamycin\", \"vonamycin powder v\")" 5 "g" "c(\"10995-9\", \"25262-7\")"
"NET" 441306 "Netilmicin" "Aminoglycosides" "c(\"J01GB07\", \"S01AA23\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "neti" "c(\"netillin\", \"netilmicin\", \"netilmicin sulfate\", \"netilmicina\", \"netilmicine\", \"netilmicinum\", \"netilyn\", \"netira\", \"vectacin\")" 0.35 "g" 0.35 "g" "c(\"25263-5\", \"3848-9\", \"3849-7\", \"3850-5\", \"47385-0\", \"59565-2\", \"59566-0\", \"59567-8\")"
"NIC" 9507 "Nicarbazin" "Other antibacterials" "" "c(\"nicarb\", \"nicarbasin\", \"nicarbazin\", \"nicarbazine\", \"nicoxin\", \"nicrazin\", \"nicrazine\", \"nirazin\")" "character(0)"
"NIF" 71946 "Nifuroquine" "Quinolones" "" "c(\"nifuroquina\", \"nifuroquine\", \"nifuroquinum\", \"quinaldofur\")" "character(0)"
"NFR" 9571062 "Nifurtoinol" "Other antibacterials" "J01XE02" "Other antibacterials" "Nitrofuran derivatives" "" "c(\"levantin\", \"nifurtoinol\", \"nifurtoinolo\", \"nifurtoinolum\", \"urfadin\", \"urfadine\", \"urfadyn\")" 0.16 "g" "character(0)"
"NTZ" 41684 "Nitazoxanide" "Other antibacterials" "P01AX11" "" "c(\"adrovet\", \"alinia\", \"azt + nitazoxanide\", \"colufase\", \"cryptaz\", \"dexidex\", \"heliton\", \"kidonax\", \"nitaxozanid\", \"nitaxozanide\", \"nitazox\", \"nitazoxamide\", \"nitazoxanid\", \"nitazoxanida\", \"nitazoxanide\", \"nitazoxanidum\", \"omniparax\", \"pacovanton\", \"paramix\", \"taenitaz\")" 1 "g" "character(0)"
"NIT" 6604200 "Nitrofurantoin" "Other antibacterials" "J01XE01" "Other antibacterials" "Nitrofuran derivatives" "c(\"f\", \"f/m\", \"fd\", \"ft\", \"ni\", \"nit\", \"nitr\")" "c(\"alfuran\", \"benkfuran\", \"berkfuran\", \"berkfurin\", \"ceduran\", \"chemiofuran\", \"cistofuran\", \"cyantin\", \"cystit\", \"dantafur\", \"fua med\", \"fuamed\", \"furabid\", \"furachel\", \"furadantin\", \"furadantin retard\", \"furadantina mc\", \"furadantine\", \"furadantine mc\", \"furadantoin\", \"furadoin\", \"furadoine\", \"furadonin\", \"furadonine\", \"furadoninum\", \"furadontin\", \"furadoxyl\", \"furalan\", \"furaloid\", \"furantoin\", \"furantoina\", \"furatoin\", \"furedan\", \"furina\", \"furobactina\", \"furodantin\", \"furophen t\", \"gerofuran\",
\"io>>uss>>a<<ixoo\", \"ituran\", \"ivadantin\", \"macpac\", \"macrobid\", \"macrodantin\", \"macrodantina\", \"macrofuran\", \"macrofurin\", \"nierofu\", \"nifurantin\", \"nifuretten\", \"nitoin\", \"nitrex\", \"nitrofuradantin\", \"nitrofurantion\", \"nitrofurantoin\", \"nitrofurantoin macro\", \"nitrofurantoina\", \"nitrofurantoine\", \"nitrofurantoinum\", \"novofuran\", \"orafuran\", \"parfuran\", \"phenurin\", \"piyeloseptyl\", \"siraliden\", \"trantoin\", \"uerineks\", \"urantoin\", \"urizept\", \"urodin\", \"urofuran\", \"urofurin\", \"urolisa\", \"urolong\",
\"uvamin\", \"welfurin\", \"zoofurin\")" 0.2 "g" "3860-4"
"NIZ" 5447130 "Nitrofurazone" "Other antibacterials" "" "c(\"acutol\", \"aldomycin\", \"alfucin\", \"amifur\", \"babrocid\", \"becafurazone\", \"biofuracina\", \"biofurea\", \"chemofuran\", \"chixin\", \"cocafurin\", \"coxistat\", \"dermofural\", \"dymazone\", \"dynazone\", \"eldezol\", \"fedacin\", \"flavazone\", \"fracine\", \"furacilin\", \"furacilinum\", \"furacillin\", \"furacin\", \"furacine\", \"furacinetten\", \"furacoccid\", \"furacort\", \"furacycline\", \"furaderm\", \"furagent\", \"furalcyn\", \"furaldon\", \"furalone\", \"furametral\", \"furaplast\", \"furaseptyl\", \"furaskin\", \"furatsilin\", \"furaziline\", \"furazin\",
\"furazina\", \"furazol w\", \"furazone\", \"furazyme\", \"furesol\", \"furfurin\", \"furosem\", \"fuvacillin\", \"hemofuran\", \"ibiofural\", \"mammex\", \"mastofuran\", \"monafuracin\", \"monafuracis\", \"monofuracin\", \"nfz mix\", \"nifucin\", \"nifurid\", \"nifuzon\", \"nitrofural\", \"nitrofuralum\", \"nitrofuran\", \"nitrofurane\", \"nitrofurazan\", \"nitrofurazone\", \"nitrofurazonum\", \"nitrofurol\", \"nitrozone\", \"otofural\", \"otofuran\", \"rivafurazon\", \"sanfuran\", \"vabrocid\", \"vadrocid\", \"yatrocin\")" "character(0)"
"NTR" 19910 "Nitroxoline" "Quinolones" "J01XX07" "Other antibacterials" "Other antibacterials" "" "c(\"galinok\", \"isinok\", \"nibiol\", \"nicene forte\", \"nitroxolin\", \"nitroxolina\", \"nitroxoline\", \"nitroxolinum\", \"notroxoline\", \"noxibiol\")" 1 "g" "character(0)"
"NOR" 4539 "Norfloxacin" "Quinolones" "c(\"J01MA06\", \"S01AE02\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"nor\", \"norf\", \"nx\", \"nxn\")" "c(\"baccidal\", \"barazan\", \"chibroxin\", \"chibroxine\", \"chibroxol\", \"fulgram\", \"gonorcin\", \"lexinor\", \"nolicin\", \"noracin\", \"noraxin\", \"norflo\", \"norfloxacin\", \"norfloxacine\", \"norfloxacino\", \"norfloxacinum\", \"norocin\", \"noroxin\", \"noroxine\", \"norxacin\", \"sebercim\", \"uroxacin\", \"utinor\", \"zoroxin\")" 0.8 "g" "3867-9"
"NVA" 10419027 "Norvancomycin" "Glycopeptides" "" "norvancomycin" "character(0)"
"NOV" 54675769 "Novobiocin" "Other antibacterials" "novo" "c(\"albamix\", \"albamycin\", \"cardelmycin\", \"cathocin\", \"cathomycin\", \"crystallinic acid\", \"inamycin\", \"novobiocin\", \"novobiocina\", \"novobiocine\", \"novobiocinum\", \"robiocina\", \"sirbiocina\", \"spheromycin\", \"stilbiocina\", \"streptonivicin\")" "17378-1"
"NYS" 6433272 "Nystatin" "Antifungals/antimycotics" "c(\"A07AA02\", \"D01AA01\", \"G01AA01\")" "nyst" "c(\"biofanal\", \"candex lotion\", \"comycin\", \"diastatin\", \"herniocid\", \"moronal\", \"myconystatin\", \"mycostatin\", \"mycostatin pastilles\", \"mykinac\", \"mykostatyna\", \"nilstat\", \"nistatin\", \"nistatina\", \"nyamyc\", \"nyotran\", \"nyotrantrade mark\", \"nystaform\", \"nystan\", \"nystatin\", \"nystatin a\", \"nystatin g\", \"nystatin lf\", \"nystatine\", \"nystatinum\", \"nystatyna\", \"nystavescent\", \"nystex\", \"nystop\", \"stamycin\", \"terrastatin\", \"zydin e\")" 1.5 "MU" "character(0)"
"OFX" 4583 "Ofloxacin" "Quinolones" "c(\"J01MA01\", \"S01AE01\", \"S02AA16\")" "Quinolone antibacterials" "Fluoroquinolones" "c(\"of\", \"ofl\", \"oflo\", \"ofx\")" "c(\"bactocin\", \"danoflox\", \"effexin\", \"exocin\", \"exocine\", \"flobacin\", \"flodemex\", \"flotavid\", \"flovid\", \"floxal\", \"floxil\", \"floxin\", \"floxin otic\", \"floxstat\", \"fugacin\", \"inoflox\", \"kinflocin\", \"kinoxacin\", \"levofloxacin hcl\", \"liflox\", \"loxinter\", \"marfloxacin\", \"medofloxine\", \"mergexin\", \"monoflocet\", \"novecin\", \"nufafloqo\", \"occidal\", \"ocuflox\", \"oflocee\", \"oflocet\", \"oflocin\", \"oflodal\", \"oflodex\", \"oflodura\", \"ofloxacin\", \"ofloxacin otic\", \"ofloxacina\", \"ofloxacine\", \"ofloxacino\", \"ofloxacinum\",
\"ofloxin\", \"onexacin\", \"operan\", \"orocin\", \"otonil\", \"oxaldin\", \"pharflox\", \"praxin\", \"puiritol\", \"qinolon\", \"quinolon\", \"quotavil\", \"sinflo\", \"tabrin\", \"taravid\", \"tariflox\", \"tarivid\", \"telbit\", \"tructum\", \"uro tarivid\", \"viotisone\", \"visiren\", \"zanocin\")" 0.4 "g" 0.4 "g" "c(\"25264-3\", \"3877-8\")"
"OLE" 72493 "Oleandomycin" "Macrolides/lincosamides" "J01FA05" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"amimycin\", \"landomycin\", \"matromycin\", \"oleandomycin a\", \"romicil\")" 1 "g" "character(0)"
"OMC" 54697325 "Omadacycline" "Tetracyclines" "J01AA15" "" "c(\"amadacycline\", \"omadacycline\")" 0.3 "g" 0.1 "g" "character(0)"
"OPT" 87880 "Optochin" "Other antibacterials" "" "c(\"numoquin\", \"optochin\", \"optoquine\")" "character(0)"
"ORB" 60605 "Orbifloxacin" "Quinolones" "" "orbifloxacin" "character(0)"
"ORI" 16136912 "Oritavancin" "Glycopeptides" "J01XA05" "Other antibacterials" "Glycopeptide antibacterials" "orit" "oritavancin" "character(0)"
"ORS" "Ormetroprim/sulfamethoxazole" "Other antibacterials" "" "" ""
"ORN" 28061 "Ornidazole" "Other antibacterials" "c(\"G01AF06\", \"J01XD03\", \"P01AB03\")" "Other antibacterials" "Imidazole derivatives" "" "c(\"madelen\", \"ornidal\", \"ornidazol\", \"ornidazole\", \"ornidazolum\", \"tiberal\")" 1.5 "g" 1 "g" "character(0)"
"OXA" 6196 "Oxacillin" "Beta-lactams/penicillins" "J01CF04" "Beta-lactam antibacterials, penicillins" "Beta-lactamase resistant penicillins" "c(\"ox\", \"oxa\", \"oxac\", \"oxal\", \"oxs\")" "c(\"bactocill\", \"ossacillina\", \"oxacilina\", \"oxacillin\", \"oxacillin sodium\", \"oxacilline\", \"oxacillinum\", \"oxazocillin\", \"oxazocilline\", \"prostaphlin\", \"prostaphlyn\", \"sodium oxacillin\")" 2 "g" 2 "g" "c(\"25265-0\", \"3882-8\")"
"OXO" 4628 "Oxolinic acid" "Quinolones" "J01MB05" "Quinolone antibacterials" "Other quinolones" "" "c(\"acide oxolinique\", \"acido ossolico\", \"acido oxolinico\", \"acidum oxolinicum\", \"aqualinic\", \"cistopax\", \"dioxacin\", \"emyrenil\", \"gramurin\", \"inoxyl\", \"nidantin\", \"oksaren\", \"orthurine\", \"ossian\", \"oxoboi\", \"oxolinic\", \"oxolinic acid\", \"pietil\", \"prodoxal\", \"prodoxol\", \"starner\", \"tiurasin\", \"ultibid\", \"urinox\", \"uritrate\", \"urotrate\", \"uroxol\", \"utibid\")" 1 "g" "character(0)"
"OXY" 54675779 "Oxytetracycline" "Tetracyclines" "c(\"D06AA03\", \"G01AA07\", \"J01AA06\", \"S01AA04\")" "Tetracyclines" "Tetracyclines" "" "c(\"adamycin\", \"berkmycen\", \"biostat\", \"biostat pa\", \"dabicycline\", \"dalimycin\", \"embryostat\", \"fanterrin\", \"galsenomycin\", \"geomycin\", \"geotilin\", \"hydroxytetracyclinum\", \"imperacin\", \"lenocycline\", \"macocyn\", \"medamycin\", \"mepatar\", \"oksisyklin\", \"ossitetraciclina\", \"oxacycline\", \"oxitetraciclina\", \"oxitetracyclin\", \"oxitetracycline\", \"oxitetracyclinum\", \"oxydon\", \"oxymycin\", \"oxymykoin\", \"oxypam\", \"oxysteclin\", \"oxyterracin\", \"oxyterracine\", \"oxyterracyne\", \"oxytetracid\", \"oxytetracyclin\", \"oxytetracycline\",
\"oxytetracycline base\", \"oxytetracyclinum\", \"proteroxyna\", \"riomitsin\", \"ryomycin\", \"solkaciclina\", \"stecsolin\", \"stevacin\", \"tarocyn\", \"tarosin\", \"teravit\", \"terrafungine\", \"terramitsin\", \"terramycin\", \"terramycin im\", \"tetran\", \"unimycin\", \"ursocyclin\", \"ursocycline\", \"vendarcin\")" 1 "g" 1 "g" "c(\"17396-3\", \"25266-8\", \"87595-5\")"
"OZN" "Ozenoxacin" "" "" ""
"PAS" 4649 "P-aminosalicylic acid" "Antimycobacterials" "" "c(\"aminopar\", \"aminosalicylic\", \"aminosalicylic acid\", \"aminosalyl\", \"aminox\", \"apacil\", \"deapasil\", \"entepas\", \"ferrosan\", \"gabbropas\", \"helipidyl\", \"hellipidyl\", \"neopasalate\", \"osacyl\", \"pamacyl\", \"pamisyl\", \"paramycin\", \"parasal\", \"parasalicil\", \"parasalindon\", \"pasalon\", \"pasara\", \"pascorbic\", \"pasdium\", \"paser granules\", \"paskalium\", \"pasmed\", \"pasnodia\", \"pasolac\", \"propasa\", \"rezipas\", \"teebacin\", \"wln: zr cq dvq\")" "character(0)"
"PAN" 72015 "Panipenem" "Carbapenems" "" "c(\"panipenem\", \"panipenemum\", \"penipanem\")" "character(0)"
"PAR" 165580 "Paromomycin" "Other antibacterials" "A07AA06" "" "c(\"aminosidin\", \"aminosidine\", \"aminosidine i\", \"aminosidine sulfate\", \"amminosidin\", \"crestomycin\", \"estomycin\", \"gabbromicina\", \"gabbromycin\", \"gabromycin\", \"humatin\", \"humycin\", \"hydroxymycin\", \"hydroxymycin sulfate\", \"monomycin\", \"monomycin a\", \"neomycin e\", \"paramomycin\", \"paramomycin sulfate\", \"paromomicina\", \"paromomycin\", \"paromomycin i\", \"paromomycine\", \"paromomycinum\", \"paucimycin\", \"paucimycinum\", \"quintomycin c\")" 3 "g" "character(0)"
"PAZ" 65957 "Pazufloxacin" "Quinolones" "J01MA18" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"pazufloxacin\", \"pazufloxacine\", \"pazufloxacino\", \"pazufloxacinum\")" 1 "g" "character(0)"
"PEF" 51081 "Pefloxacin" "Quinolones" "J01MA03" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"pefl\")" "c(\"abactal\", \"labocton\", \"pefloxacin\", \"pefloxacine\", \"pefloxacino\", \"pefloxacinum\", \"perfloxacin\", \"silver pefloxacin\")" 0.8 "g" 0.8 "g" "3906-5"
"PNM" 10250769 "Penamecillin" "Beta-lactams/penicillins" "J01CE06" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"hydroxymethyl\", \"penamecilina\", \"penamecillin\", \"penamecillina\", \"penamecilline\", \"penamecillinum\")" 1.05 "g" "character(0)"
"PNO" "Penicillin/novobiocin" "Beta-lactams/penicillins" "" "" ""
"PSU" "Penicillin/sulbactam" "Beta-lactams/penicillins" "" "" ""
"PNM1" 54686187 "Penimepicycline" "Tetracyclines" "J01AA10" "Tetracyclines" "Tetracyclines" "" "c(\"duamine\", \"hydrocycline\", \"penetracyne\", \"penimepiciclina\", \"penimepicycline\", \"penimepicyclinum\")" "character(0)"
"PIM" 65453 "Pentisomicin" "Aminoglycosides" "" "c(\"pentisomicin\", \"pentisomicina\", \"pentisomicine\", \"pentisomicinum\")" "character(0)"
"PTZ" 55250256 "Pentizidone" "Other antibacterials" "" "" ""
"PEX" 16132253 "Pexiganan" "Other antibacterials" "" "pexiganan" "character(0)"
"PHE" 272833 "Phenethicillin" "Beta-lactams/penicillins" "J01CE05" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "c(\"\", \"fene\")" "c(\"feneticilina\", \"feneticillina\", \"feneticilline\", \"k phenethicillin\", \"phenethicilin\", \"phenethicillinum\", \"pheneticillin\", \"pheneticilline\", \"pheneticillinum\", \"phenoxy pc\", \"potassium penicillin\")" 1 "g" "41471-4"
"PHN" 6869 "Phenoxymethylpenicillin" "Beta-lactams/penicillins" "J01CE02" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "c(\"fepe\", \"peni v\", \"penicillin v\", \"pnv\", \"pv\")" "c(\"acipen v\", \"apocillin\", \"apopen\", \"beromycin\", \"calcipen\", \"compocillin v\", \"crystapen v\", \"distaquaine v\", \"eskacillian v\", \"eskacillin v\", \"fenacilin\", \"fenospen\", \"meropenin\", \"oracillin\", \"oratren\", \"penicillin v\", \"phenocillin\", \"phenomycilline\", \"phenopenicillin\", \"robicillin\", \"rocilin\", \"stabicillin\", \"vebecillin\", \"veetids\", \"vegacillin\")" 2 "g" "character(0)"
"PMR" 5284447 "Pimaricin" "Antifungals/antimycotics" "c(\"\", \"natamycin\")" "c(\"delvocid\", \"mycophyt\", \"myprozine\", \"natacyn\", \"natamicina\", \"natamycin\", \"natamycine\", \"natamycinum\", \"pimafucin\", \"pimaracin\", \"pimarizin\", \"synogil\", \"tennecetin\")" "character(0)"
"PPA" 4831 "Pipemidic acid" "Quinolones" "J01MB04" "Quinolone antibacterials" "Other quinolones" "c(\"pipz\", \"pizu\")" "c(\"acide pipemidique\", \"acido pipemidico\", \"acidum pipemidicum\", \"deblaston\", \"dolcol\", \"pipedac\", \"pipemid\", \"pipemidic\", \"pipemidic acid\", \"pipemidicacid\", \"pipram\", \"uromidin\")" 0.8 "g" "character(0)"
"PIP" 43672 "Piperacillin" "Beta-lactams/penicillins" "J01CA12" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"pi\", \"pip\", \"pipc\", \"pipe\", \"pp\")" "c(\"isipen\", \"pentcillin\", \"peperacillin\", \"peracin\", \"piperacilina\", \"piperacillin\", \"piperacillin na\", \"piperacillin sodium\", \"piperacilline\", \"piperacillinum\", \"pipercillin\", \"pipracil\", \"pipril\")" 14 "g" "c(\"25268-4\", \"3972-7\")"
"PIS" "Piperacillin/sulbactam" "Beta-lactams/penicillins" "" "" ""
"TZP" 461573 "Piperacillin/tazobactam" "Beta-lactams/penicillins" "J01CR05" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"p/t\", \"piptaz\", \"piptazo\", \"pit\", \"pita\", \"pt\", \"ptc\", \"ptz\", \"tzp\")" "c(\"\", \"tazocel\", \"tazocillin\", \"tazocin\", \"zosyn\")" 14 "g" "character(0)"
"PRC" 71978 "Piridicillin" "Beta-lactams/penicillins" "" "piridicillin" "character(0)"
"PRL" 157385 "Pirlimycin" "Macrolides/lincosamides" "" "c(\"pirlimycin\", \"pirlimycina\", \"pirlimycine\", \"pirlimycinum\", \"pirsue\")" "character(0)"
"PIR" 4855 "Piromidic acid" "Quinolones" "J01MB03" "Quinolone antibacterials" "Other quinolones" "" "c(\"acide piromidique\", \"acido piromidico\", \"acidum piromidicum\", \"actrun c\", \"bactramyl\", \"enterol\", \"gastrurol\", \"panacid\", \"pirodal\", \"piromidic acid\", \"pyrido\", \"reelon\", \"septural\", \"urisept\", \"uropir\", \"zaomeal\")" 2 "g" "character(0)"
"PVM" 33478 "Pivampicillin" "Beta-lactams/penicillins" "J01CA02" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"berocillin\", \"pivaloylampicillin\", \"pivampicilina\", \"pivampicillin\", \"pivampicilline\", \"pivampicillinum\", \"pondocillin\")" 1.05 "g" "character(0)"
"PME" 115163 "Pivmecillinam" "Beta-lactams/penicillins" "J01CA08" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"amdinocillin pivoxil\", \"coactabs\", \"hydroxymethyl\", \"pivmecilinamo\", \"pivmecillinam\", \"pivmecillinam hcl\", \"pivmecillinamum\")" 0.6 "g" "character(0)"
"PLZ" 42613186 "Plazomicin" "Aminoglycosides" "J01GB14" "" "plazomicin" "92024-9"
"PLB" 49800004 "Polymyxin B" "Polymyxins" "c(\"A07AA05\", \"J01XB02\", \"S01AA18\", \"S02AA11\", \"S03AA03\")" "Other antibacterials" "Polymyxins" "c(\"pb\", \"pol\", \"polb\", \"poly\", \"poly b\", \"polymixin\", \"polymixin b\")" "c(\"polimixina b\", \"polumyxin b\", \"polymixin b\", \"polymyxine b\")" 3 "MU" 0.15 "g" "c(\"17473-0\", \"25269-2\")"
"POP" "Polymyxin B/polysorbate 80" "Polymyxins" "" "" ""
"POS" 468595 "Posaconazole" "Antifungals/antimycotics" "J02AC04" "Antimycotics for systemic use" "Triazole derivatives" "posa" "c(\"noxafil\", \"posaconazole\", \"posaconazole sp\", \"posconazole\")" 0.3 "g" 0.3 "g" "c(\"53731-6\", \"80545-7\")"
"PRA" 9802884 "Pradofloxacin" "Quinolones" "" "pradofloxacin" "character(0)"
"PRX" 71455 "Premafloxacin" "Quinolones" "" "premafloxacin" "character(0)"
"PMD" 456199 "Pretomanid" "Antimycobacterials" "J04AK08" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "" "" ""
"PRM" 6446787 "Primycin" "Macrolides/lincosamides" "" "" ""
"PRI" 11979535 "Pristinamycin" "Macrolides/lincosamides" "J01FG01" "Macrolides, lincosamides and streptogramins" "Streptogramins" "c(\"\", \"pris\")" "c(\"eskalin v\", \"mikamycin\", \"mikamycine\", \"mikamycinum\", \"ostreogrycinum\", \"pristinamycine\", \"pristinamycinum\", \"stafac\", \"stafytracine\", \"staphylomycin\", \"starfac\", \"streptogramin\", \"vernamycin\", \"virgimycin\", \"virgimycine\", \"virginiamycina\", \"virginiamycine\", \"virginiamycinum\")" 2 "g" "character(0)"
"PRB" 5903 "Procaine benzylpenicillin" "Beta-lactams/penicillins" "J01CE09" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"depocillin\", \"duphapen\", \"hostacillin\", \"hydracillin\", \"jenacillin o\", \"nopcaine\", \"penicillin procaine\", \"retardillin\", \"vetspen\", \"vitablend\")" 0.6 "g" "character(0)"
"PRP" 92879 "Propicillin" "Beta-lactams/penicillins" "J01CE03" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"propicilina\", \"propicillin\", \"propicilline\", \"propicillinum\")" 0.9 "g" "character(0)"
"PKA" 9872451 "Propikacin" "Aminoglycosides" "" "c(\"propikacin\", \"propikacina\", \"propikacine\", \"propikacinum\")" "character(0)"
"PTH" 666418 "Prothionamide" "Antimycobacterials" "J04AD01" "Drugs for treatment of tuberculosis" "Thiocarbamide derivatives" "prot" "c(\"ektebin\", \"peteha\", \"prothionamide\", \"prothionamidum\", \"protion\", \"protionamid\", \"protionamida\", \"protionamide\", \"protionamidum\", \"protionizina\", \"tebeform\", \"trevintix\", \"tuberex\")" 0.75 "g" "character(0)"
"PRU" 65947 "Prulifloxacin" "Quinolones" "J01MA17" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"prulifloxacin\", \"pruvel\", \"pufloxacin dioxolil\", \"quisnon\")" 0.6 "g" "character(0)"
"PZA" 1046 "Pyrazinamide" "Antimycobacterials" "J04AK01" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "pyra" "c(\"aldinamid\", \"aldinamide\", \"braccopiral\", \"corsazinmid\", \"dipimide\", \"eprazin\", \"farmizina\", \"isopas\", \"lynamide\", \"novamid\", \"p ezetamid\", \"pezetamid\", \"pharozinamide\", \"piraldina\", \"pirazimida\", \"pirazinamid\", \"pirazinamida\", \"pirazinamide\", \"prazina\", \"pyrafat\", \"pyramide\", \"pyrazide\", \"pyrazinamdie\", \"pyrazinamid\", \"pyrazinamide\", \"pyrazinamidum\", \"pyrazine carboxamide\", \"pyrazineamide\", \"pyrizinamide\", \"rifafour\", \"rozide\", \"tebrazid\", \"tebrazio\", \"tisamid\", \"unipyranamide\", \"zinamide\", \"zinastat\"
)" 1.5 "g" "c(\"11001-5\", \"25270-0\")"
"QDA" 11979418 "Quinupristin/dalfopristin" "Macrolides/lincosamides" "J01FG02" "Macrolides, lincosamides and streptogramins" "Streptogramins" "c(\"q/d\", \"qda\", \"qida\", \"quda\", \"rp\", \"syn\")" "" 1.5 "g" ""
"RAC" 56052 "Ractopamine" "Other antibacterials" "" "c(\"ractopamina\", \"ractopamine\", \"ractopaminum\")" "character(0)"
"RAM" 16132338 "Ramoplanin" "Glycopeptides" "" "ramoplanin" "character(0)"
"RZM" 10993211 "Razupenem" "Carbapenems" "" "razupenem" "character(0)"
"RTP" 6918462 "Retapamulin" "Other antibacterials" "D06AX13" "Antibiotics for topical use" "Other antibiotics for topical use" "c(\"\", \"ret\")" "c(\"altabax\", \"altargo\", \"retapamulin\")" "character(0)"
"RZF" "Rezafungin" "Antifungals" "" "" ""
"RBC" 44631912 "Ribociclib" "Antifungals/antimycotics" "L01EF02" "Antimycotics for systemic use" "Triazole derivatives" "ribo" "c(\"kisqali\", \"ribociclib\")" "character(0)"
"RST" 33042 "Ribostamycin" "Aminoglycosides" "J01GB10" "Aminoglycoside antibacterials" "Other aminoglycosides" "" "c(\"dekamycin iv\", \"hetangmycin\", \"ribastamin\", \"ribostamicina\", \"ribostamycin\", \"ribostamycine\", \"ribostamycinum\", \"vistamycin\", \"xylostatin\")" 1 "g" "character(0)"
"RID1" 16659285 "Ridinilazole" "Other antibacterials" "" "ridinilazole" "character(0)"
"RIB" 135398743 "Rifabutin" "Antimycobacterials" "J04AB04" "Drugs for treatment of tuberculosis" "Antibiotics" "rifb" "c(\"alfacid\", \"ansamicin\", \"ansamycin\", \"ansatipin\", \"ansatipine\", \"mycobutin\", \"rifabutin\", \"rifabutina\", \"rifabutine\", \"rifabutinum\")" 0.15 "g" "24032-5"
"RIF" 135398735 "Rifampicin" "Antimycobacterials" "J04AB02" "Drugs for treatment of tuberculosis" "Antibiotics" "rifa" "c(\"abrifam\", \"archidyn\", \"arficin\", \"arzide\", \"azt + rifampin\", \"benemicin\", \"benemycin\", \"dipicin\", \"doloresum\", \"eremfat\", \"famcin\", \"fenampicin\", \"rifadin\", \"rifadin i.v\", \"rifadin i.v.\", \"rifadine\", \"rifagen\", \"rifaldazin\", \"rifaldazine\", \"rifaldin\", \"rifamate\", \"rifamicin amp\", \"rifamor\", \"rifampicin\", \"rifampicin sv\", \"rifampicina\", \"rifampicine\", \"rifampicinum\", \"rifampin\", \"rifamsolin\", \"rifamycin amp\", \"rifaprodin\", \"rifcin\", \"rifobac\", \"rifoldin\", \"rifoldine\", \"riforal\", \"rimactan\", \"rimactane\",
\"rimactizid\", \"rimazid\", \"rimycin\", \"sinerdol\", \"tubocin\")" 0.6 "g" 0.6 "g" "character(0)"
"RFI" "Rifampicin/isoniazid" "Antimycobacterials" "J04AM02" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "c(\"rifinah\", \"rimactazid\")" "character(0)"
"RPEI" "Rifampicin/pyrazinamide/ethambutol/isoniazid" "Antimycobacterials" "J04AM06" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""
"RPI" "Rifampicin/pyrazinamide/isoniazid" "Antimycobacterials" "J04AM05" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""
"RFM" 6324616 "Rifamycin" "Antimycobacterials" "c(\"A07AA13\", \"D06AX15\", \"J04AB03\", \"S01AA16\", \"S02AA12\")" "Drugs for treatment of tuberculosis" "Antibiotics" "" "c(\"aemcolo\", \"rifacin\", \"rifamicina\", \"rifamicine sv\", \"rifamycin\", \"rifamycine\", \"rifamycinum\", \"rifocin\", \"rifocyn\", \"rifomycin\", \"rifomycin sv\", \"tuborin\")" 0.6 "g" "character(0)"
"RFP" 135403821 "Rifapentine" "Antimycobacterials" "J04AB05" "Drugs for treatment of tuberculosis" "Antibiotics" "c(\"rifp\", \"rpt\")" "c(\"cyclopentyl rifampin\", \"priftin\", \"rifapentin\", \"rifapentina\", \"rifapentine\", \"rifapentinum\")" 0.11 "g" "character(0)"
"RFX" 6436173 "Rifaximin" "Other antibacterials" "c(\"A07AA11\", \"D06AX11\")" "Intestinal antiinfectives" "Antibiotics" "" "c(\"fatroximin\", \"flonorm\", \"lormyx\", \"lumenax\", \"normix\", \"redactiv\", \"rifacol\", \"rifamixin\", \"rifaxidin\", \"rifaximin\", \"rifaximina\", \"rifaximine\", \"rifaximinum\", \"rifaxin\", \"ritacol\", \"spiraxin\", \"xifaxan\", \"xifaxsan\")" 0.6 "g" "character(0)"
"RIT" 65633 "Ritipenem" "Carbapenems" "" "ritipenem" "character(0)"
"RIA" 163692 "Ritipenem acoxil" "Carbapenems" "" "ritipenem acoxil" "character(0)"
"ROK" 5282211 "Rokitamycin" "Macrolides/lincosamides" "J01FA12" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"propionylleucomycin\", \"ricamycin\", \"rokicid\", \"rokital\", \"rokitamicina\", \"rokitamycin\", \"rokitamycine\", \"rokitamycinum\")" 0.8 "g" "character(0)"
"RLT" 54682938 "Rolitetracycline" "Tetracyclines" "J01AA09" "Tetracyclines" "Tetracyclines" "" "c(\"bristacin\", \"kinteto\", \"reverin\", \"rolitetraciclina\", \"rolitetracycline\", \"rolitetracyclinum\", \"solvocillin\", \"superciclin\", \"synotodecin\", \"synterin\", \"syntetrex\", \"syntetrin\", \"velacicline\", \"velacycline\")" 0.35 "g" "character(0)"
"ROS" 287180 "Rosoxacin" "Quinolones" "J01MB01" "Quinolone antibacterials" "Other quinolones" "" "c(\"acrosoxacin\", \"eracine\", \"eradacil\", \"eradacin\", \"rosoxacin\", \"rosoxacine\", \"rosoxacino\", \"rosoxacinum\", \"roxadyl\", \"winuron\")" 0.3 "g" "character(0)"
"RXT" "Roxithromycin" "Macrolides/lincosamides" "J01FA06" "Macrolides, lincosamides and streptogramins" "Macrolides" "roxi" "" 0.3 "g" ""
"RFL" 58258 "Rufloxacin" "Quinolones" "J01MA10" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"rufloxacin\", \"rufloxacin hcl\", \"rufloxacine\", \"rufloxacino\", \"rufloxacinum\")" 0.2 "g" "character(0)"
"SAL" 3085092 "Salinomycin" "Other antibacterials" "" "c(\"coxistac\", \"procoxacin\", \"salinomicina\", \"salinomycin\", \"salinomycine\", \"salinomycinum\")" "87593-0"
"SAR" 56208 "Sarafloxacin" "Quinolones" "" "c(\"difloxacine\", \"difloxacino\", \"difloxacinum\", \"saraflox\", \"sarafloxacin\", \"sarafloxacine\", \"sarafloxacino\", \"sarafloxacinum\")" "character(0)"
"SRX" 9933415 "Sarmoxicillin" "Beta-lactams/penicillins" "" "sarmoxicillin" "character(0)"
"SEC" 71815 "Secnidazole" "Other antibacterials" "P01AB07" "" "c(\"flagentyl\", \"secnidal\", \"secnidazol\", \"secnidazole\", \"secnidazolum\", \"secnil\", \"sindose\", \"solosec\")" 2 "g" "character(0)"
"SMF" "Simvastatin/fenofibrate" "Antimycobacterials" "C10BA04" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "simv" "" ""
"SIS" 36119 "Sisomicin" "Aminoglycosides" "J01GB08" "Aminoglycoside antibacterials" "Other aminoglycosides" "siso" "c(\"rickamicin\", \"salvamina\", \"siseptin sulfate\", \"sisomicin\", \"sisomicin sulfate\", \"sisomicina\", \"sisomicine\", \"sisomicinum\", \"sisomin\", \"sisomycin\", \"sissomicin\", \"sizomycin\")" 0.24 "g" "character(0)"
"SIT" 461399 "Sitafloxacin" "Quinolones" "J01MA21" "" "c(\"gracevit\", \"sitafloxacinisomer\")" 0.1 "g" "character(0)"
"SDA" 2724368 "Sodium aminosalicylate" "Antimycobacterials" "J04AA02" "Drugs for treatment of tuberculosis" "Aminosalicylic acid and derivatives" "" "c(\"bactylan\", \"decapasil\", \"lepasen\", \"monopas\", \"nippas\", \"p.a.s. sodium\", \"pamisyl sodium\", \"parasal sodium\", \"pas sodium\", \"pasade\", \"pasnal\", \"passodico\", \"salvis\", \"sanipirol\", \"sodiopas\", \"sodium p.a.s\", \"sodium pas\", \"teebacin\", \"tubersan\")" 14 "g" 14 "g" "character(0)"
"SOL" 25242512 "Solithromycin" "Macrolides/lincosamides" "J01FA16" "" "" ""
"SPX" 60464 "Sparfloxacin" "Quinolones" "J01MA09" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"spa\", \"spar\")" "c(\"esparfloxacino\", \"sparfloxacin\", \"sparfloxacine\", \"sparfloxacinum\")" 0.2 "g" "character(0)"
"SPT" 15541 "Spectinomycin" "Other antibacterials" "J01XX04" "Other antibacterials" "Other antibacterials" "c(\"sc\", \"spe\", \"spec\", \"spt\")" "c(\"actinospectacina\", \"adspec\", \"espectinomicina\", \"prospec\", \"specitinomycin\", \"spectam\", \"spectinomicina\", \"spectinomycin\", \"spectinomycin di hcl\", \"spectinomycine\", \"spectinomycinum\", \"stanilo\", \"togamycin\", \"trobicin\")" 3 "g" "character(0)"
"SPI" 6419898 "Spiramycin" "Macrolides/lincosamides" "J01FA02" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"\", \"spir\")" "c(\"espiramicin\", \"provamycin\", \"rovamycin\", \"rovamycine\", \"sequamycin\", \"spiramycine\", \"spiramycinum\")" 3 "g" "character(0)"
"SPM" "Spiramycin/metronidazole" "Other antibacterials" "J01RA04" "Combinations of antibacterials" "Combinations of antibacterials" "" "" ""
"STR" "Streptoduocin" "Aminoglycosides" "J01GA02" "Aminoglycoside antibacterials" "Streptomycins" "" "" 1 "g" ""
"STR1" 19649 "Streptomycin" "Aminoglycosides" "c(\"A07AA04\", \"J01GA01\")" "Aminoglycoside antibacterials" "Streptomycins" "c(\"s\", \"stm\", \"str\", \"stre\")" "c(\"agrept\", \"agrimycin\", \"chemform\", \"estreptomicina\", \"neodiestreptopab\", \"strepcen\", \"streptomicina\", \"streptomycin\", \"streptomycin a\", \"streptomycin spx\", \"streptomycin sulfate\", \"streptomycine\", \"streptomyzin\", \"vetstrep\")" 1 "g" "4039-4"
"STH" "Streptomycin-high" "Aminoglycosides" "c(\"sthi\", \"sthl\", \"strepto high\", \"streptomycin high\")" "" ""
"STI" "Streptomycin/isoniazid" "Antimycobacterials" "J04AM01" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""
"SUL" 130313 "Sulbactam" "Beta-lactams/penicillins" "J01CG01" "Beta-lactam antibacterials, penicillins" "Beta-lactamase inhibitors" "" "c(\"betamaze\", \"sulbactam\", \"sulbactam acid\", \"sulbactam free acid\", \"sulbactamum\")" 1 "g" "character(0)"
"SBC" 20055036 "Sulbenicillin" "Beta-lactams/penicillins" "J01CA16" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"kedacillina\", \"sulbenicilina\", \"sulbenicilline\", \"sulbenicillinum\")" 15 "g" "character(0)"
"SUC" 5318 "Sulconazole" "Antifungals/antimycotics" "D01AC09" "" "c(\"sulconazol\", \"sulconazole\", \"sulconazolum\")" "character(0)"
"SUP" 6634 "Sulfachlorpyridazine" "Other antibacterials" "" "c(\"cluricol\", \"cosulid\", \"cosumix\", \"durasulf\", \"nefrosul\", \"nsulfanilamide\", \"prinzone vet\", \"prinzone vet.\", \"solfaclorpiridazina\", \"sonilyn\", \"sulfachlorpyridazine\", \"sulfacloropiridazina\", \"vetisulid\")" "character(0)"
"SDI" 5215 "Sulfadiazine" "Trimethoprims" "J01EC02" "Sulfonamides and trimethoprim" "Intermediate-acting sulfonamides" "" "c(\"adiazin\", \"adiazine\", \"cocodiazine\", \"codiazine\", \"cremodiazine\", \"cremotres\", \"debenal\", \"deltazina\", \"diazin\", \"diazolone\", \"diazovit\", \"diazyl\", \"eskadiazine\", \"honey diazine\", \"liquadiazine\", \"microsulfon\", \"neazine\", \"neotrizine\", \"nsulfanilamide\", \"palatrize\", \"piridisir\", \"pirimal\", \"pyrimal\", \"quadetts\", \"quadramoid\", \"sanodiazine\", \"sildaflo\", \"silvadene\", \"solfadiazina\", \"spofadrizine\", \"sterazine\", \"sulfacombin\", \"sulfadiazene\", \"sulfadiazin\", \"sulfadiazina\", \"sulfadiazine\", \"sulfadiazinum\",
\"sulfapirimidin\", \"sulfapyrimidin\", \"sulfapyrimidine\", \"sulfatryl\", \"sulfazine\", \"sulfolex\", \"sulfonamides duplex\", \"sulfonsol\", \"sulfose\", \"sulphadiazine\", \"sulphadiazine e\", \"terfonyl\", \"theradiazine\", \"thermazene\", \"trifonamide\", \"triple sulfa\", \"triple sulfas\", \"trisem\", \"truozine\", \"zinc sulfadiazine\")" 0.6 "g" "c(\"27216-1\", \"59742-7\", \"6907-0\")"
"SLT" 122284 "Sulfadiazine/tetroxoprim" "Trimethoprims" "J01EE06" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "" "" ""
"SLT1" 64932 "Sulfadiazine/trimethoprim" "Trimethoprims" "J01EE02" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "" "c(\"antastmon\", \"cotrimazine\", \"diaziprim forte\", \"ditrim\", \"ditrivet\", \"sultrisan\", \"triglobe\", \"trimin\", \"tucoprim\", \"uniprim\")" "character(0)"
"SUD" 5323 "Sulfadimethoxine" "Trimethoprims" "J01ED01" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"agribon\", \"arnosulfan\", \"bactrovet\", \"deposul\", \"diasulfa\", \"diasulfyl\", \"dimetazina\", \"dinosol\", \"dorisul\", \"lasibon\", \"madribon\", \"madrigid\", \"madriqid\", \"madroxin\", \"madroxine\", \"maxulvet\", \"mecozine\", \"memcozine\", \"metoxidon\", \"neostrepal\", \"neostreptal\", \"nsulfanilamide\", \"omnibon\", \"persulfen\", \"primor\", \"radonin\", \"redifal\", \"rofenaid\", \"roscosulf\", \"scandisil\", \"solfadimetossina\", \"sudine\", \"suldixine\", \"sulfabon\", \"sulfadimethoxin\", \"sulfadimethoxine\", \"sulfadimethoxinum\", \"sulfadimetossina\",
\"sulfadimetoxin\", \"sulfadimetoxina\", \"sulfadimetoxine\", \"sulfastop\", \"sulfdimethoxine\", \"sulfoplan\", \"sulphadimethoxine\", \"sulxin\", \"sumbio\", \"symbio\", \"theracanzan\", \"ultrasulfon\")" 0.5 "g" "character(0)"
"SDM" 5327 "Sulfadimidine" "Trimethoprims" "J01EB03" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"azolmetazin\", \"benzene sulfonamide\", \"calfspan\", \"calfspan tablets\", \"cremomethazine\", \"diazil\", \"diazilsulfadine\", \"dimezathine\", \"intradine\", \"kelametazine\", \"mermeth\", \"metazin\", \"neasina\", \"neazina\", \"nsulfanilamide\", \"panazin\", \"pirmazin\", \"primazin\", \"sa iii\", \"solfadimidina\", \"spanbolet\", \"sulfadimerazine\", \"sulfadimesin\", \"sulfadimesine\", \"sulfadimethyldiazine\", \"sulfadimezin\", \"sulfadimezine\", \"sulfadimezinum\", \"sulfadimidin\", \"sulfadimidina\", \"sulfadimidine\", \"sulfadimidinum\", \"sulfadine\",
\"sulfametazina\", \"sulfametazyny\", \"sulfamethazine\", \"sulfamethiazine\", \"sulfamezathine\", \"sulfamidine\", \"sulfasure sr bolus\", \"sulfodimesin\", \"sulfodimezine\", \"sulka k boluses\", \"sulka s boluses\", \"sulmet\", \"sulphadimidine\", \"sulphamethasine\", \"sulphamethazine\", \"sulphamezathine\", \"sulphamidine\", \"sulphodimezine\", \"superseptil\", \"superseptyl\", \"vertolan\")" 4 "g" "character(0)"
"SLT2" "Sulfadimidine/trimethoprim" "Trimethoprims" "J01EE05" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "" "" ""
"SLF" 5344 "Sulfafurazole" "Trimethoprims" "c(\"J01EB05\", \"S01AB02\")" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "c(\"\", \"sfsz\")" "c(\"accuzole\", \"alphazole\", \"amidoxal\", \"astrazolo\", \"azo gantrisin\", \"azosulfizin\", \"bactesulf\", \"barazae\", \"chemouag\", \"cosoxazole\", \"dorsulfan\", \"dorsulfan warthausen\", \"entusil\", \"entusul\", \"eryzole\", \"gantrisin\", \"gantrisine\", \"gantrisona\", \"gantrizin\", \"gantrosan\", \"isoxamin\", \"neazolin\", \"neoxazoi\", \"neoxazol\", \"novazolo\", \"novosaxazole\", \"nsulfanilamide\", \"nsulphanilamide\", \"pancid\", \"pediazole\", \"renosulfan\", \"resoxol\", \"roxosul\", \"roxosul tablets\", \"roxoxol\", \"saxosozine\", \"sodizole\", \"solfafurazolo\",
\"soxamide\", \"soxazole\", \"soxisol\", \"soxitabs\", \"soxomide\", \"stansin\", \"sulbio\", \"sulfafuraz ole\", \"sulfafurazol\", \"sulfafurazole\", \"sulfafurazolum\", \"sulfagan\", \"sulfagen\", \"sulfaisoxazole\", \"sulfalar\", \"sulfapolar\", \"sulfasol\", \"sulfasoxazole\", \"sulfasoxizole\", \"sulfazin\", \"sulfisin\", \"sulfisonazole\", \"sulfisoxasole\", \"sulfisoxazol\", \"sulfisoxazole\", \"sulfisoxazolum\", \"sulfizin\", \"sulfizol\", \"sulfizole\", \"sulfofurazole\", \"sulfoxol\", \"suloxsol\", \"sulphafuraz\", \"sulphafurazol\", \"sulphafurazole\", \"sulphafurazolum\",
\"sulphaisoxazole\", \"sulphisoxazol\", \"sulphisoxazole\", \"sulphofurazole\", \"sulsoxin\", \"thiasin\", \"unisulf\", \"urisoxin\", \"uritrisin\", \"urogan\", \"vagilia\")" 4 "g" 4 "g" "character(0)"
"SLF1" 5343 "Sulfaisodimidine" "Trimethoprims" "J01EB01" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"aristamid\", \"aristamide\", \"aristogyn\", \"domain\", \"domian\", \"elcosin\", \"elcosine\", \"elkosil\", \"elkosin\", \"elkosine\", \"erycon\", \"isosulf\", \"mefenal\", \"nsulfanilamide\", \"solfisomidina\", \"sulfadimetine\", \"sulfaisodimerazine\", \"sulfaisodimidine\", \"sulfaisodimidinum\", \"sulfaisomidine\", \"sulfamethin\", \"sulfasomidine\", \"sulfisomidina\", \"sulfisomidine\", \"sulfisomidine sodium\", \"sulfisomidinum\", \"sulphasomidine\")" 4 "g" 4 "g" "character(0)"
"SLF2" 9047 "Sulfalene" "Trimethoprims" "J01ED02" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"dalysep\", \"kelfizin\", \"kelfizina\", \"kelfizine\", \"kelfizine w\", \"longum\", \"nsulfanilamide\", \"policydal\", \"polycidal\", \"solfametopirazina\", \"sulfalen\", \"sulfalene\", \"sulfaleno\", \"sulfalenum\", \"sulfamethopyrazine\", \"sulfamethoxypyrazine\", \"sulfametopyrazine\", \"sulfametoxypyridazin\", \"sulphalene\", \"sulphametopyrazine\", \"vetkelfizina\")" 0.1 "g" "character(0)"
"SZO" 187764 "Sulfamazone" "Trimethoprims" "J01ED09" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"sulfamazon\", \"sulfamazona\", \"sulfamazone\", \"sulfamazonum\")" 1.5 "g" "character(0)"
"SLF3" 5325 "Sulfamerazine" "Trimethoprims" "c(\"D06BA06\", \"J01ED07\")" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"cremomerazine\", \"kelamerazine\", \"mebacid\", \"mesulfa\", \"methylpyrimal\", \"methylsulfazin\", \"methylsulfazine\", \"metilsulfadiazin\", \"metilsulfazin\", \"nsulfanilamide\", \"percoccide\", \"pyralcid\", \"pyrimal m\", \"romezin\", \"septacil\", \"septosyl\", \"solfamerazina\", \"solumedin\", \"sulfameradine\", \"sulfamerazin\", \"sulfamerazina\", \"sulfamerazine\", \"sulfamerazinum\", \"sulfamethyldiazine\", \"sulphamerazine\", \"sumedine\", \"susfamerazine\")" 3 "g" "character(0)"
"SLT3" "Sulfamerazine/trimethoprim" "Trimethoprims" "J01EE07" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "" "" ""
"SUM" 5327 "Sulfamethazine" "Other antibacterials" "" "c(\"azolmetazin\", \"benzene sulfonamide\", \"calfspan\", \"calfspan tablets\", \"cremomethazine\", \"diazil\", \"diazilsulfadine\", \"dimezathine\", \"intradine\", \"kelametazine\", \"mermeth\", \"metazin\", \"neasina\", \"neazina\", \"nsulfanilamide\", \"panazin\", \"pirmazin\", \"primazin\", \"sa iii\", \"solfadimidina\", \"spanbolet\", \"sulfadimerazine\", \"sulfadimesin\", \"sulfadimesine\", \"sulfadimethyldiazine\", \"sulfadimezin\", \"sulfadimezine\", \"sulfadimezinum\", \"sulfadimidin\", \"sulfadimidina\", \"sulfadimidine\", \"sulfadimidinum\", \"sulfadine\",
\"sulfametazina\", \"sulfametazyny\", \"sulfamethazine\", \"sulfamethiazine\", \"sulfamezathine\", \"sulfamidine\", \"sulfasure sr bolus\", \"sulfodimesin\", \"sulfodimezine\", \"sulka k boluses\", \"sulka s boluses\", \"sulmet\", \"sulphadimidine\", \"sulphamethasine\", \"sulphamethazine\", \"sulphamezathine\", \"sulphamidine\", \"sulphodimezine\", \"superseptil\", \"superseptyl\", \"vertolan\")" "87592-2"
"SLF4" 5328 "Sulfamethizole" "Trimethoprims" "c(\"B05CA04\", \"D06BA04\", \"J01EB02\", \"S01AB01\")" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "c(\"\", \"sfmz\")" "c(\"ayerlucil\", \"lucosil\", \"methazol\", \"microsul\", \"nsulfanilamide\", \"proklar\", \"renasul\", \"salimol\", \"solfametizolo\", \"sulamethizole\", \"sulfa gram\", \"sulfamethizol\", \"sulfamethizole\", \"sulfamethizolum\", \"sulfametizol\", \"sulfapyelon\", \"sulfstat\", \"sulfurine\", \"sulphamethizole\", \"tetracid\", \"thidicur\", \"thiosulfil\", \"thiosulfil forte\", \"ultrasul\", \"urocydal\", \"urodiaton\", \"urolucosil\", \"urosulfin\")" 4 "g" "c(\"60175-7\", \"60176-5\", \"60177-3\")"
"SMX" 5329 "Sulfamethoxazole" "Trimethoprims" "J01EC01" "Sulfonamides and trimethoprim" "Intermediate-acting sulfonamides" "c(\"sfmx\", \"sulf\")" "c(\"azo gantanol\", \"eusaprim\", \"gamazole\", \"gantanol\", \"gantanol ds\", \"metoxal\", \"nsulfanilamide\", \"nsulphanilamide\", \"radonil\", \"septran\", \"septrin\", \"simsinomin\", \"sinomin\", \"solfametossazolo\", \"sulfamethalazole\", \"sulfamethoxazol\", \"sulfamethoxazole\", \"sulfamethoxazolum\", \"sulfamethoxizole\", \"sulfamethylisoxazole\", \"sulfametoxazol\", \"sulfisomezole\", \"sulphamethalazole\", \"sulphamethoxazol\", \"sulphamethoxazole\", \"sulphisomezole\", \"urobak\")" 2 "g" "c(\"10342-4\", \"25271-8\", \"39772-9\", \"59971-2\", \"59972-0\", \"60333-2\", \"72674-5\", \"80549-9\", \"80974-9\")"
"SLF5" 5330 "Sulfamethoxypyridazine" "Trimethoprims" "J01ED05" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"altezol\", \"davosin\", \"depovernil\", \"kineks\", \"lederkyn\", \"lentac\", \"lisulfen\", \"longin\", \"medicel\", \"midicel\", \"midikel\", \"myasul\", \"nsulfanilamide\", \"opinsul\", \"paramid\", \"paramid supra\", \"petrisul\", \"piridolo\", \"quinoseptyl\", \"retamid\", \"retasulfin\", \"retasulphine\", \"slosul\", \"spofadazine\", \"sulfalex\", \"sulfapyridazine\", \"sulfdurazin\", \"sulfozona\", \"sultirene\", \"vinces\")" 0.5 "g" "character(0)"
"SLF6" 19596 "Sulfametomidine" "Trimethoprims" "J01ED03" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"duroprocin\", \"methofadin\", \"methofazine\", \"nsulfanilamide\", \"solfametomidina\", \"sulfamethomidine\", \"sulfametomidin\", \"sulfametomidina\", \"sulfametomidine\", \"sulfametomidinum\")" "character(0)"
"SLF7" 5326 "Sulfametoxydiazine" "Trimethoprims" "J01ED04" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"bayrena\", \"berlicid\", \"dairena\", \"durenat\", \"juvoxin\", \"kinecid\", \"kirocid\", \"longasulf\", \"methoxypyrimal\", \"nsulfanilamide\", \"solfametossidiazina\", \"sulfameter\", \"sulfamethorine\", \"sulfamethoxine\", \"sulfamethoxydiazin\", \"sulfamethoxydiazine\", \"sulfamethoxydin\", \"sulfamethoxydine\", \"sulfametin\", \"sulfametinum\", \"sulfametorin\", \"sulfametorine\", \"sulfametorinum\", \"sulfametoxidiazina\", \"sulfametoxidine\", \"sulfametoxydiazine\", \"sulfametoxydiazinum\", \"sulphameter\", \"sulphamethoxydiazine\", \"supramid\",
\"ultrax\")" 0.5 "g" "character(0)"
"SLT4" "Sulfametrole/trimethoprim" "Trimethoprims" "J01EE03" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "c(\"\", \"trsm\")" "" ""
"SLF8" 12894 "Sulfamoxole" "Trimethoprims" "J01EC03" "Sulfonamides and trimethoprim" "Intermediate-acting sulfonamides" "" "c(\"justamil\", \"nsulfanilamide\", \"oxasulfa\", \"solfamossolo\", \"sulfadimethyloxazole\", \"sulfamoxol\", \"sulfamoxole\", \"sulfamoxolum\", \"sulfano\", \"sulfavigor\", \"sulfmidil\", \"sulfono\", \"sulfune\", \"sulfuno\", \"sulphamoxole\", \"tardamid\", \"tardamide\")" 1 "g" 1 "g" "character(0)"
"SLT5" "Sulfamoxole/trimethoprim" "Trimethoprims" "J01EE04" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "" "" ""
"SLF9" 5333 "Sulfanilamide" "Trimethoprims" "c(\"D06BA05\", \"J01EB06\")" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"albexan\", \"albosal\", \"ambeside\", \"antistrept\", \"astreptine\", \"astrocid\", \"bacteramid\", \"bactesid\", \"collomide\", \"colsulanyde\", \"copticide\", \"deseptyl\", \"desseptyl\", \"dipron\", \"ergaseptine\", \"erysipan\", \"estreptocida\", \"exoseptoplix\", \"gerison\", \"gombardol\", \"infepan\", \"lysococcine\", \"neococcyl\", \"orgaseptine\", \"prontalbin\", \"prontosil album\", \"prontosil i\", \"prontosil white\", \"prontylin\", \"pronzin album\", \"proseptal\", \"proseptine\", \"proseptol\", \"pysococcine\", \"rubiazol a\", \"sanamid\", \"septamide album\",
\"septanilam\", \"septinal\", \"septolix\", \"septoplex\", \"septoplix\", \"solfanilamide\", \"stopton album\", \"stramid\", \"strepamide\", \"strepsan\", \"streptagol\", \"streptamid\", \"streptamin\", \"streptasol\", \"streptocid\", \"streptocid album\", \"streptocide\", \"streptocide white\", \"streptocidum\", \"streptoclase\", \"streptocom\", \"streptol\", \"strepton\", \"streptopan\", \"streptosil\", \"streptozol\", \"streptozone\", \"streptrocide\", \"sulfamidyl\", \"sulfamine\", \"sulfana\", \"sulfanalone\", \"sulfanidyl\", \"sulfanil\", \"sulfanilamida\", \"sulfanilamide\",
\"sulfanilamidum\", \"sulfanilimidic acid\", \"sulfanimide\", \"sulfocidin\", \"sulfocidine\", \"sulfonamide\", \"sulfonamide p\", \"sulfonylamide\", \"sulphanilamide\", \"sulphanilamide gr\", \"sulphonamide\", \"therapol\", \"tolder\", \"white streptocide\", \"wln: zswr dz\")" "character(0)"
"SLF10" 68933 "Sulfaperin" "Trimethoprims" "J01ED06" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"anastaf\", \"archisulfa\", \"avissul\", \"chemiopen\", \"demosulfan\", \"durisan saft\", \"ipersulfidin sirup\", \"isosulfamerazine\", \"methylsulfadiazin\", \"novosul\", \"nsulfanilamide\", \"orosulfan\", \"pallidin\", \"retardon\", \"risulfasens\", \"sulfaperin\", \"sulfaperina\", \"sulfaperine\", \"sulfaperinum\", \"sulfatreis\", \"sulfopirimidine\", \"sulpenta\", \"ultrasulfon sirup\")" 0.5 "g" "character(0)"
"SLF11" 5335 "Sulfaphenazole" "Trimethoprims" "J01ED08" "Sulfonamides and trimethoprim" "Long-acting sulfonamides" "" "c(\"depocid\", \"depotsulfonamide\", \"eftolon\", \"firmazolo\", \"inamil\", \"isarol\", \"isarol v\", \"merian\", \"microtan pirazolo\", \"nsulfanilamide\", \"orisul\", \"orisulf\", \"paidazolo\", \"phenylsulfapyrazole\", \"plisulfan\", \"raziosulfa\", \"solfafenazolo\", \"sulfabid\", \"sulfafenazol\", \"sulfafenazolo\", \"sulfaphenazol\", \"sulfaphenazole\", \"sulfaphenazolum\", \"sulfaphenazon\", \"sulfaphenylpipazol\", \"sulfaphenylpyrazol\", \"sulfaphenylpyrazole\", \"sulfonylpyrazol\", \"sulphaphenazole\", \"sulphenazole\")" 1 "g" "character(0)"
"SLF12" 5336 "Sulfapyridine" "Trimethoprims" "J01EB04" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"adiplon\", \"coccoclase\", \"dagenan\", \"eubasin\", \"eubasinum\", \"haptocil\", \"piridazol\", \"plurazol\", \"pyriamid\", \"pyridazol\", \"relbapiridina\", \"septipulmon\", \"solfapiridina\", \"streptosilpyridine\", \"sulfapiridina\", \"sulfapyridin\", \"sulfapyridine\", \"sulfapyridinum\", \"sulfidin\", \"sulfidine\", \"sulphapyridin\", \"sulphapyridine\", \"thioseptal\", \"trianon\")" 1 "g" "c(\"14075-6\", \"55580-5\")"
"SNA" 60582 "Sulfasuccinamide" "Other antibacterials" "" "c(\"ambesid\", \"derganil\", \"sulfasuccinamid\", \"sulfasuccinamida\", \"sulfasuccinamide\", \"sulfasuccinamidum\")" "character(0)"
"SUT" 5340 "Sulfathiazole" "Trimethoprims" "c(\"D06BA02\", \"J01EB07\")" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"azoquimiol\", \"azoseptale\", \"cerazol\", \"cerazole\", \"chemosept\", \"cibazol\", \"duatok\", \"dulana\", \"eleudron\", \"enterobiocine\", \"estafilol\", \"formosulfathiazole\", \"neostrepsan\", \"norsulfasol\", \"norsulfazol\", \"norsulfazole\", \"norsulfazolum\", \"nsulfanilamide\", \"planomide\", \"poliseptil\", \"sanotiazol\", \"septozol\", \"solfatiazolo\", \"streptosilthiazole\", \"sulfamul\", \"sulfathiazol\", \"sulfathiazole\", \"sulfathiazolum\", \"sulfatiazol\", \"sulfavitina\", \"sulfocerol\", \"sulphathiazole\", \"sulzol\", \"thiacoccine\", \"thiasulfol\",
\"thiazamide\", \"thiozamide\", \"wintrazole\")" "87591-4"
"SLF13" 3000579 "Sulfathiourea" "Trimethoprims" "J01EB08" "Sulfonamides and trimethoprim" "Short-acting sulfonamides" "" "c(\"badional\", \"baldinol\", \"fontamide\", \"salvoseptyl\", \"solfatiourea\", \"solufontamide\", \"sulfanilthiourea\", \"sulfathiocarbamid\", \"sulfathiocarbamide\", \"sulfathiocarbamidum\", \"sulfathiourea\", \"sulfathiouree\", \"sulfatiourea\", \"sulphathiourea\")" 6 "g" "character(0)"
"SOX" 5344 "Sulfisoxazole" "Other antibacterials" "" "c(\"accuzole\", \"alphazole\", \"amidoxal\", \"astrazolo\", \"azo gantrisin\", \"azosulfizin\", \"bactesulf\", \"barazae\", \"chemouag\", \"cosoxazole\", \"dorsulfan\", \"dorsulfan warthausen\", \"entusil\", \"entusul\", \"eryzole\", \"gantrisin\", \"gantrisine\", \"gantrisona\", \"gantrizin\", \"gantrosan\", \"isoxamin\", \"neazolin\", \"neoxazoi\", \"neoxazol\", \"novazolo\", \"novosaxazole\", \"nsulfanilamide\", \"nsulphanilamide\", \"pancid\", \"pediazole\", \"renosulfan\", \"resoxol\", \"roxosul\", \"roxosul tablets\", \"roxoxol\", \"saxosozine\", \"sodizole\", \"solfafurazolo\",
\"soxamide\", \"soxazole\", \"soxisol\", \"soxitabs\", \"soxomide\", \"stansin\", \"sulbio\", \"sulfafuraz ole\", \"sulfafurazol\", \"sulfafurazole\", \"sulfafurazolum\", \"sulfagan\", \"sulfagen\", \"sulfaisoxazole\", \"sulfalar\", \"sulfapolar\", \"sulfasol\", \"sulfasoxazole\", \"sulfasoxizole\", \"sulfazin\", \"sulfisin\", \"sulfisonazole\", \"sulfisoxasole\", \"sulfisoxazol\", \"sulfisoxazole\", \"sulfisoxazolum\", \"sulfizin\", \"sulfizol\", \"sulfizole\", \"sulfofurazole\", \"sulfoxol\", \"suloxsol\", \"sulphafuraz\", \"sulphafurazol\", \"sulphafurazole\", \"sulphafurazolum\",
\"sulphaisoxazole\", \"sulphisoxazol\", \"sulphisoxazole\", \"sulphofurazole\", \"sulsoxin\", \"thiasin\", \"unisulf\", \"urisoxin\", \"uritrisin\", \"urogan\", \"vagilia\")" "9701-4"
"SSS" 86225 "Sulfonamide" "Other antibacterials" "c(\"\", \"sfna\")" "" ""
"SLP" 9950244 "Sulopenem" "Other antibacterials" "" "sulopenem" "character(0)"
"SLT6" 444022 "Sultamicillin" "Beta-lactams/penicillins" "J01CR04" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "" "c(\"sultamicilina\", \"sultamicillin\", \"sultamicillinum\")" 1.5 "g" "character(0)"
"SUR" 46700778 "Surotomycin" "Other antibacterials" "" "surotomycin" "character(0)"
"TAL" 71447 "Talampicillin" "Beta-lactams/penicillins" "J01CA15" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"talampicilina\", \"talampicillin\", \"talampicilline\", \"talampicillinum\")" 2 "g" "character(0)"
"TLP" 163307 "Talmetoprim" "Other antibacterials" "" "talmetoprim" "character(0)"
"TAZ" 123630 "Tazobactam" "Beta-lactams/penicillins" "J01CG02" "Beta-lactam antibacterials, penicillins" "Beta-lactamase inhibitors" "tazo" "c(\"tazobactam\", \"tazobactam acid\", \"tazobactamum\", \"tazobactum\")" "character(0)"
"TBP" 9800194 "Tebipenem" "Carbapenems" "" "" ""
"TZD" 11234049 "Tedizolid" "Oxazolidinones" "J01XX11" "Other antibacterials" "Other antibacterials" "tedi" "c(\"tedizolid\", \"torezolid\")" 0.2 "g" 0.2 "g" "character(0)"
"TEC" 16131923 "Teicoplanin" "Glycopeptides" "J01XA02" "Other antibacterials" "Glycopeptide antibacterials" "c(\"tec\", \"tei\", \"teic\", \"tp\", \"tpl\", \"tpn\")" "c(\"targocid\", \"tecoplanina\", \"tecoplanine\", \"tecoplaninum\", \"teichomycin\", \"teicoplanina\", \"teicoplanine\", \"teicoplaninum\")" 0.4 "g" "c(\"25534-9\", \"25535-6\", \"34378-0\", \"34379-8\", \"4043-6\", \"80968-1\")"
"TCM" "Teicoplanin-macromethod" "Glycopeptides" "" "" ""
"TLV" 3081362 "Telavancin" "Glycopeptides" "J01XA03" "Other antibacterials" "Glycopeptide antibacterials" "tela" "c(\"telavancin\", \"vibativ\")" "character(0)"
"TLT" 3002190 "Telithromycin" "Macrolides/lincosamides" "J01FA15" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"\", \"teli\")" "levviax" 0.8 "g" "character(0)"
"TMX" 60021 "Temafloxacin" "Quinolones" "J01MA05" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"tema\")" "c(\"omniflox\", \"temafloxacin\", \"temafloxacina\", \"temafloxacine\", \"temafloxacinum\")" 0.8 "g" "character(0)"
"TEM" 171758 "Temocillin" "Beta-lactams/penicillins" "J01CA17" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"\", \"temo\")" "c(\"temocilina\", \"temocillin\", \"temocillina\", \"temocilline\", \"temocillinum\")" 4 "g" "character(0)"
"TRB" 1549008 "Terbinafine" "Antifungals/antimycotics" "c(\"D01AE15\", \"D01BA02\")" "Antifungals for systemic use" "Antifungals for systemic use" "c(\"\", \"terb\")" "c(\"corbinal\", \"lamasil\", \"lamisil\", \"lamisil at\", \"lamisil tablet\", \"terbinafina\", \"terbinafine\", \"terbinafinum\", \"terbinex\")" 0.25 "g" "character(0)"
"TRC" 441383 "Terconazole" "Antifungals/antimycotics" "G01AG02" "" "c(\"fungistat\", \"panlomyc\", \"terazol\", \"terconazol\", \"terconazole\", \"terconazolum\", \"tercospor\", \"triaconazole\", \"zazole\")" "character(0)"
"TRZ" 65720 "Terizidone" "Antimycobacterials" "J04AK03" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "" "c(\"terivalidin\", \"terizidon\", \"terizidona\", \"terizidone\", \"terizidonum\")" "character(0)"
"TCY" 54675776 "Tetracycline" "Tetracyclines" "c(\"A01AB13\", \"D06AA04\", \"J01AA07\", \"S01AA09\", \"S02AA08\", \"S03AA02\")" "Tetracyclines" "Tetracyclines" "c(\"tc\", \"te\", \"tet\", \"tetr\")" "c(\"abramycin\", \"abricycline\", \"achromycin\", \"achromycin v\", \"actisite\", \"agromicina\", \"ambramicina\", \"ambramycin\", \"amycin\", \"biocycline\", \"bristaciclin\", \"bristaciclina\", \"bristacycline\", \"cefracycline\", \"centet\", \"ciclibion\", \"copharlan\", \"criseociclina\", \"cyclomycin\", \"cyclopar\", \"cytome\", \"democracin\", \"deschlorobiomycin\", \"dumocyclin\", \"enterocycline\", \"hostacyclin\", \"lexacycline\", \"limecycline\", \"liquamycin\", \"medocycline\", \"mericycline\", \"micycline\", \"neocycline\", \"oletetrin\", \"omegamycin\",
\"orlycycline\", \"panmycin\", \"piracaps\", \"polycycline\", \"polyotic\", \"purocyclina\", \"resteclin\", \"robitet\", \"roviciclina\", \"sigmamycin\", \"solvocin\", \"sumycin\", \"sumycin syrup\", \"tetrabon\", \"tetrachel\", \"tetraciclina\", \"tetracycl\", \"tetracyclin\", \"tetracycline\", \"tetracycline base\", \"tetracycline i\", \"tetracycline ii\", \"tetracyclinum\", \"tetracyn\", \"tetradecin\", \"tetrafil\", \"tetramed\", \"tetrasure\", \"tetraverine\", \"tetrazyklin\", \"tetrex\", \"topicycline\", \"tsiklomistsin\", \"tsiklomitsin\", \"veracin\", \"vetacyclinum\"
)" 1 "g" 1 "g" "c(\"25272-6\", \"4045-1\", \"87590-6\")"
"TET" 65450 "Tetroxoprim" "Other antibacterials" "" "c(\"tetroxoprim\", \"tetroxoprima\", \"tetroxoprime\", \"tetroxoprimum\")" "character(0)"
"THA" 9568512 "Thiacetazone" "Oxazolidinones" "" "c(\"aktivan\", \"ambathizon\", \"amithiozone\", \"amithizone\", \"amitiozon\", \"benthiozone\", \"benzothiozane\", \"benzothiozon\", \"berculon a\", \"berkazon\", \"citazone\", \"conteben\", \"diasan\", \"diazan\", \"domakol\", \"ilbion\", \"livazone\", \"mirizone neustab\", \"mivizon\", \"myvizone\", \"neotibil\", \"neustab\", \"novakol\", \"nuclon argentinian\", \"panrone\", \"parazone\", \"seroden\", \"siocarbazone\", \"tebalon\", \"tebecure\", \"tebemar\", \"tebesone i\", \"tebethion\", \"tebethione\", \"tebezon\", \"thiacetazone\", \"thiacetone\", \"thiacetozone\",
\"thibon\", \"thibone\", \"thioacetazon\", \"thioacetazone\", \"thioacetazonum\", \"thioazetazone\", \"thiocarbazil\", \"thiomicid\", \"thionicid\", \"thioparamizon\", \"thioparamizone\", \"thiosemicarbarzone\", \"thiosemicarbazone\", \"thiotebesin\", \"thiotebezin\", \"thiotebicina\", \"thizone\", \"tiacetazon\", \"tibicur\", \"tibion\", \"tibione\", \"tibizan\", \"tibone\", \"tioacetazon\", \"tioacetazona\", \"tioatsetazon\", \"tiobicina\", \"tiocarone\", \"tiosecolo\", \"tubercazon\", \"tubigal\")" "character(0)"
"THI" 27200 "Thiamphenicol" "Amphenicols" "J01BA02" "Amphenicols" "Amphenicols" "" "c(\"descocin\", \"dexawin\", \"dextrosulfenidol\", \"dextrosulphenidol\", \"efnicol\", \"hyrazin\", \"igralin\", \"macphenicol\", \"masatirin\", \"neomyson\", \"racefenicol\", \"racefenicolo\", \"racefenicolum\", \"raceophenidol\", \"racephenicol\", \"rincrol\", \"thiamcol\", \"thiamphenicol\", \"thiamphenicolum\", \"thiocymetin\", \"thiomycetin\", \"thiophenicol\", \"tiamfenicol\", \"tiamfenicolo\", \"urfamicina\", \"urfamycine\", \"vicemycetin\")" 1.5 "g" 1.5 "g" "character(0)"
"THI1" "Thioacetazone/isoniazid" "Antimycobacterials" "J04AM04" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""
"TIA" 656958 "Tiamulin" "Other antibacterials" "" "c(\"denagard\", \"tiamulin\", \"tiamulin pamoate\", \"tiamulina\", \"tiamuline\", \"tiamulinum\")" "87589-8"
"TIC" 36921 "Ticarcillin" "Beta-lactams/penicillins" "J01CA13" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"tc\", \"ti\", \"tic\", \"tica\")" "c(\"ticarcilina\", \"ticarcillin\", \"ticarcilline\", \"ticarcillinum\", \"ticillin\")" 15 "g" "c(\"25254-4\", \"4054-3\", \"4055-0\")"
"TCC" 6437075 "Ticarcillin/clavulanic acid" "Beta-lactams/penicillins" "J01CR03" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"t/c\", \"tcc\", \"ticl\", \"tim\", \"tlc\")" "timentin" 15 "g" "character(0)"
"TGC" 54686904 "Tigecycline" "Tetracyclines" "J01AA12" "Tetracyclines" "Tetracyclines" "c(\"tgc\", \"tig\", \"tige\")" "c(\"haizheng li xing\", \"tigeciclina\", \"tigecyclin\", \"tigecycline\", \"tigecycline hydrate\", \"tigecyclinum\", \"tigilcycline\", \"tygacil\")" 0.1 "g" "character(0)"
"TBQ" 65592 "Tilbroquinol" "Quinolones" "P01AA05" "" "c(\"tilbroquinol\", \"tilbroquinolum\")" "character(0)"
"TIP" 24860548 "Tildipirosin" "Macrolides/lincosamides" "" "c(\"tildipirosin\", \"zuprevo\")" "character(0)"
"TIL" 5282521 "Tilmicosin" "Macrolides/lincosamides" "" "c(\"micotil\", \"pulmotil\", \"tilmicosin\", \"tilmicosina\", \"tilmicosine\", \"tilmicosinum\")" "87588-0"
"TIN" 5479 "Tinidazole" "Other antibacterials" "c(\"J01XD02\", \"P01AB02\")" "Other antibacterials" "Imidazole derivatives" "c(\"\", \"tini\")" "c(\"amtiba\", \"bioshik\", \"ethyl sulfone\", \"fasigin\", \"fasigyn\", \"fasigyntrade mark\", \"fasygin\", \"glongyn\", \"haisigyn\", \"pletil\", \"simplotan\", \"simplotantrade mark\", \"sorquetan\", \"tindamax\", \"tindamaxtrade mark\", \"tinidazol\", \"tinidazole\", \"tinidazolum\", \"tricolam\", \"trimonase\")" 2 "g" 1.5 "g" "character(0)"
"TCR" 3001386 "Tiocarlide" "Antimycobacterials" "J04AD02" "Drugs for treatment of tuberculosis" "Thiocarbamide derivatives" "" "c(\"amixyl\", \"datanil\", \"disocarban\", \"disoxyl\", \"thiocarlide\", \"tiocarlid\", \"tiocarlida\", \"tiocarlide\", \"tiocarlidum\")" 7 "g" "character(0)"
"TDC" 10247721 "Tiodonium chloride" "Other antibacterials" "" "c(\"cloruro de tiodonio\", \"tiodonii chloridum\", \"tiodonium chloride\")" "character(0)"
"TXC" 65788 "Tioxacin" "Quinolones" "" "c(\"tioxacin\", \"tioxacine\", \"tioxacino\", \"tioxacinum\", \"tioxic acid\")" "character(0)"
"TIZ" 394397 "Tizoxanide" "Other antibacterials" "" "ntzdes" "character(0)"
"TOB" 36294 "Tobramycin" "Aminoglycosides" "c(\"J01GB01\", \"S01AA12\")" "Aminoglycoside antibacterials" "Other aminoglycosides" "c(\"nn\", \"tm\", \"to\", \"tob\", \"tobr\")" "c(\"bethkis\", \"brulamycin\", \"deoxykanamycin b\", \"distobram\", \"gernebcin\", \"gotabiotic\", \"kitabis pak\", \"nebcin\", \"nebicin\", \"nebramycin\", \"nebramycin vi\", \"obramycin\", \"sybryx\", \"tenebrimycin\", \"tenemycin\", \"tobacin\", \"tobi podhaler\", \"tobracin\", \"tobradex\", \"tobradistin\", \"tobralex\", \"tobramaxin\", \"tobramicin\", \"tobramicina\", \"tobramitsetin\", \"tobramycetin\", \"tobramycin\", \"tobramycin base\", \"tobramycin sulfate\", \"tobramycine\", \"tobramycinum\", \"tobrased\", \"tobrasone\", \"tobrex\")" 0.24 "g" "c(\"13584-8\", \"17808-7\", \"22750-4\", \"22751-2\", \"22752-0\", \"31094-6\", \"31095-3\", \"31096-1\", \"35239-3\", \"35670-9\", \"4057-6\", \"4058-4\", \"4059-2\", \"50927-3\", \"52962-8\", \"59380-6\", \"80966-5\")"
"TOH" "Tobramycin-high" "Aminoglycosides" "c(\"tobra high\", \"tobramycin high\", \"tohl\")" "" ""
"TFX" 5517 "Tosufloxacin" "Quinolones" "J01MA22" "" "tosufloxacin" 0.45 "g" "character(0)"
"TMP" 5578 "Trimethoprim" "Trimethoprims" "J01EA01" "Sulfonamides and trimethoprim" "Trimethoprim and derivatives" "c(\"t\", \"tmp\", \"tr\", \"tri\", \"trim\", \"w\")" "c(\"abaprim\", \"alprim\", \"anitrim\", \"antrima\", \"antrimox\", \"bacdan\", \"bacidal\", \"bacide\", \"bacterial\", \"bacticel\", \"bactifor\", \"bactin\", \"bactoprim\", \"bactramin\", \"bactrim\", \"bencole\", \"bethaprim\", \"biosulten\", \"briscotrim\", \"chemotrin\", \"colizole\", \"colizole ds\", \"conprim\", \"cotrimel\", \"cotrimoxizole\", \"deprim\", \"dosulfin\", \"duocide\", \"esbesul\", \"espectrin\", \"euctrim\", \"exbesul\", \"fermagex\", \"fortrim\", \"idotrim\", \"ikaprim\", \"instalac\", \"kombinax\", \"lagatrim\", \"lagatrim forte\", \"lastrim\", \"lescot\",
\"methoprim\", \"metoprim\", \"monoprim\", \"monotrim\", \"monotrimin\", \"novotrimel\", \"omstat\", \"oraprim\", \"pancidim\", \"polytrim\", \"priloprim\", \"primosept\", \"primsol\", \"proloprim\", \"protrin\", \"purbal\", \"resprim\", \"resprim forte\", \"roubac\", \"roubal\", \"salvatrim\", \"septrin ds\", \"septrin forte\", \"septrin s\", \"setprin\", \"sinotrim\", \"stopan\", \"streptoplus\", \"sugaprim\", \"sulfamar\", \"sulfamethoprim\", \"sulfoxaprim\", \"sulthrim\", \"sultrex\", \"syraprim\", \"tiempe\", \"tmp smx\", \"toprim\", \"trimanyl\", \"trimethioprim\", \"trimethopim\",
\"trimethoprim\", \"trimethoprime\", \"trimethoprimum\", \"trimethopriom\", \"trimetoprim\", \"trimetoprima\", \"trimexazole\", \"trimexol\", \"trimezol\", \"trimogal\", \"trimono\", \"trimopan\", \"trimpex\", \"triprim\", \"trisul\", \"trisulcom\", \"trisulfam\", \"trisural\", \"uretrim\", \"urobactrim\", \"utetrin\", \"velaten\", \"wellcoprim\", \"wellcoprin\", \"xeroprim\", \"zamboprim\")" 0.4 "g" 0.4 "g" "c(\"11005-6\", \"17747-7\", \"25273-4\", \"32342-8\", \"4079-0\", \"4080-8\", \"4081-6\", \"55584-7\", \"80552-3\", \"80973-1\")"
"SXT" 358641 "Trimethoprim/sulfamethoxazole" "Trimethoprims" "J01EE01" "Sulfonamides and trimethoprim" "Combinations of sulfonamides and trimethoprim, incl. derivatives" "c(\"cot\", \"cotrim\", \"sxt\", \"t/s\", \"trsu\", \"trsx\", \"ts\")" "c(\"bactrim\", \"bactrimel\", \"belcomycine\", \"colimycin\", \"colimycin sulphate\", \"colisticin\", \"colistimethate\", \"colistimethate sodium\", \"colistin sulfate\", \"colistin sulphate\", \"colomycin\", \"coly-mycin\", \"cotrimazole\", \"cotrimoxazole\", \"polymyxin e\", \"polymyxin e. sulfate\", \"promixin\", \"septra\", \"totazina\")" "character(0)"
"TRL" 202225 "Troleandomycin" "Macrolides/lincosamides" "J01FA08" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"acetyloleandomycin\", \"aovine\", \"cyclamycin\", \"evramicina\", \"matromicina\", \"matromycin t\", \"oleandocetine\", \"t.a.o.\", \"treolmicina\", \"tribiocillina\", \"triocetin\", \"triolan\", \"troleandomicina\", \"troleandomycin\", \"troleandomycine\", \"troleandomycinum\", \"viamicina\", \"wytrion\")" 1 "g" "character(0)"
"TRO" 55886 "Trospectomycin" "Other antibacterials" "" "c(\"trospectinomycin\", \"trospectomicina\", \"trospectomycin\", \"trospectomycine\", \"trospectomycinum\")" "character(0)"
"TVA" 62959 "Trovafloxacin" "Quinolones" "J01MA13" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"trov\")" "c(\"trovafloxacin\", \"trovan\")" 0.2 "g" 0.2 "g" "character(0)"
"TUL" 9832301 "Tulathromycin" "Macrolides/lincosamides" "" "c(\"draxxin\", \"tulathrmycin a\", \"tulathromycin\", \"tulathromycin a\")" "character(0)"
"TYL" 5280440 "Tylosin" "Macrolides/lincosamides" "" "c(\"fradizine\", \"tilosina\", \"tylocine\", \"tylosin\", \"tylosin a\", \"tylosine\", \"tylosinum\")" "87587-2"
"TYL1" 6441094 "Tylvalosin" "Macrolides/lincosamides" "c(\"\", \"tvn\")" "" ""
"PRU1" 124225 "Ulifloxacin (Prulifloxacin)" "Other antibacterials" "" "ulifloxacin" "character(0)"
"VAN" 14969 "Vancomycin" "Glycopeptides" "c(\"A07AA09\", \"J01XA01\", \"S01AA28\")" "Other antibacterials" "Glycopeptide antibacterials" "c(\"va\", \"van\", \"vanc\")" "c(\"vancocin\", \"vancocin hcl\", \"vancoled\", \"vancomicina\", \"vancomycin\", \"vancomycin hcl\", \"vancomycine\", \"vancomycinum\", \"vancor\", \"viomycin derivative\")" 2 "g" 2 "g" "c(\"13586-3\", \"13587-1\", \"20578-1\", \"31012-8\", \"39092-2\", \"39796-8\", \"39797-6\", \"4089-9\", \"4090-7\", \"4091-5\", \"4092-3\", \"50938-0\", \"59381-4\")"
"VAM" "Vancomycin-macromethod" "Glycopeptides" "" "" ""
"VIO" 135398671 "Viomycin" "Antimycobacterials" "" "c(\"celiomycin\", \"florimycin\", \"floromycin\", \"viomicina\", \"viomycin\", \"viomycine\", \"viomycinum\")" "character(0)"
"VIR" 11979535 "Virginiamycine" "Other antibacterials" "" "c(\"eskalin v\", \"mikamycin\", \"mikamycine\", \"mikamycinum\", \"ostreogrycinum\", \"pristinamycine\", \"pristinamycinum\", \"stafac\", \"stafytracine\", \"staphylomycin\", \"starfac\", \"streptogramin\", \"vernamycin\", \"virgimycin\", \"virgimycine\", \"virginiamycina\", \"virginiamycine\", \"virginiamycinum\")" "character(0)"
"VOR" 71616 "Voriconazole" "Antifungals/antimycotics" "J02AC03" "Antimycotics for systemic use" "Triazole derivatives" "c(\"vori\", \"vrc\")" "c(\"pfizer\", \"vfend i.v.\", \"voriconazol\", \"voriconazole\", \"voriconazolum\", \"vorikonazole\")" 0.4 "g" 0.4 "g" "c(\"38370-3\", \"53902-3\", \"73676-9\", \"80553-1\", \"80651-3\")"
"XBR" 72144 "Xibornol" "Other antibacterials" "J01XX02" "Other antibacterials" "Other antibacterials" "" "c(\"bactacine\", \"bracen\", \"nanbacine\", \"xibornol\", \"xibornolo\", \"xibornolum\")" "character(0)"
"ZID" 77846445 "Zidebactam" "Other antibacterials" "" "zidebactam" "character(0)"
"ZFD" "Zoliflodacin" "" "" ""
"AMA" 4649 "4-aminosalicylic acid" "Antimycobacterials"
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
7b6649442069d3d121f61ca3ff01843a
246da79545e045edac7c3ec445b3a04e
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
58d6a0589aea598420e37045fb04a5ae
21f4808065fcad26bdf869a693b074d2
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Some files were not shown because too many files have changed in this diff Show More