1
0
mirror of https://github.com/msberends/AMR.git synced 2026-09-08 22:58:55 +02:00

115 Commits

Author SHA1 Message Date
1a88caa119 (v1.5.0.9009) unit test fixes 2021-01-22 10:55:07 +01:00
1ba44776a1 (v1.5.0.9008) Internal data sets to pkg, speed for auto col determination 2021-01-22 10:20:41 +01:00
27f084d819 (v1.5.0.9007) updated unit tests 2021-01-18 18:45:43 +01:00
4eab095306 (v1.5.0.9006) major documentation update 2021-01-18 16:57:56 +01:00
e95218c0d1 (v1.5.0.9005) custom MDRO guideline 2021-01-17 10:35:21 +01:00
e699de955c (v1.5.0.9004) custom MDRO guideline 2021-01-17 00:26:48 +01:00
7ebc534ccd (v1.5.0.9003) verbose output of mdro() 2021-01-15 22:44:52 +01:00
6745f3fb17 (v1.5.0.9002) doc update 2021-01-14 15:51:41 +01:00
bc00470dca (v1.5.0.9001) more informative argument errors 2021-01-14 14:41:44 +01:00
d014955ce0 (v.1.5.0.9000) implementation of EUCAST rules v11 (2021) 2021-01-12 22:08:04 +01:00
3b84b8be75 v1.5.0 2021-01-06 11:16:17 +01:00
1563dcd1aa (v1.4.0.9062) unit test fix 2021-01-04 14:46:17 +01:00
a7ea4c9d2f (v1.4.0.9061) ab class selector fix 2021-01-04 14:16:09 +01:00
8d117820b8 (v1.4.0.9060) ab class selector fix 2021-01-04 13:39:06 +01:00
c9de74c81a (v1.4.0.9059) ab class selector fix 2021-01-04 12:29:25 +01:00
82cfa24ea4 (v1.4.0.9058) GH actions update 2021-01-04 11:27:37 +01:00
daac96fefe (v1.4.0.9057) GH actions update 2021-01-04 09:49:42 +01:00
63a4dda467 (v1.4.0.9056) subsetting ab class selectors for base R 2021-01-03 23:40:05 +01:00
ecac443f86 (v1.4.0.9055) more unit tests 2020-12-31 13:44:58 +01:00
10dec96058 (v1.4.0.9054) unit test update 2020-12-29 22:06:01 +01:00
d3f007bf65 (v1.4.0.9053) unit test old R versions 2020-12-29 21:23:01 +01:00
526f8afb08 (v1.4.0.9052) replaced all sapply's with type-safe vapply's 2020-12-28 22:24:33 +01:00
ccf13dd6c0 (v1.4.0.9051) ab class 2020-12-27 23:19:41 +01:00
afc325c314 (v1.4.0.9050) ab selectors base R 2020-12-27 20:32:40 +01:00
175e33abba (v1.4.0.9049) unit tests 2020-12-27 15:07:01 +01:00
ed198916bf (v1.4.0.9048) AmpC de-repressed cephalo-resistant mutants 2020-12-27 14:23:11 +01:00
8b52f9b1be (v1.4.0.9047) unit tests 2020-12-27 00:30:28 +01:00
acbd0cf7ca (v1.4.0.9046) get_episode 2020-12-27 00:07:00 +01:00
291f802be3 (v1.4.0.9045) unit tests 2020-12-25 00:06:11 +01:00
df37584189 (v1.4.0.9044) mo tibble printing, mo_shortname() fix 2020-12-24 23:29:10 +01:00
128ebcfd62 (v1.4.0.9043) documentation update 2020-12-22 00:51:17 +01:00
ee70883246 (v1.4.0.9042) auto dark theme website 2020-12-21 22:46:29 +01:00
81af41da3a (v1.4.0.9041) updates based on review 2020-12-17 16:22:25 +01:00
1faa816090 (v1.4.0.9040) LA-MRSA / CA-MRSA 2020-12-16 16:18:53 +01:00
203bc20eb0 (v1.4.0.9039) more unit tests 2020-12-13 20:44:32 +01:00
ac22b8d5c1 (v1.4.0.9038) docu update 2020-12-13 13:44:04 +01:00
c8bcecf232 (v1.4.0.9037) random_* functions 2020-12-12 23:17:29 +01:00
2edd3339db (v1.4.0.9036) more unit tests 2020-12-11 12:17:23 +01:00
23ddc6004b (v1.4.0.9035) eucast_rules fix 2020-12-11 09:05:03 +01:00
c9fc7e8a45 (v1.4.0.9034) MIC printing update 2020-12-09 09:40:50 +01:00
2145f1d1ba (v1.4.0.9033) documentation update 2020-12-08 12:37:25 +01:00
1bdb136b3a (v1.4.0.9032) auto-data guessing for functions 2020-12-07 16:06:42 +01:00
fdf29e6c5b (v1.4.0.9031) as.ab() fix 2020-12-03 22:30:14 +01:00
e03b3c96d3 (v1.4.0.9030) as.mo() fix for known lab codes 2020-12-03 16:59:04 +01:00
4c114ff4b4 (v1.4.0.9029) grey background for backticks, like readr pkg 2020-12-01 16:59:57 +01:00
00447c6dc4 git update 2020-11-28 22:15:44 +01:00
0e1fdb7dd7 (v1.4.0.9027) docu update 2020-11-25 20:26:02 +01:00
7b42b15c90 (v1.4.0.9026) docu update 2020-11-24 11:47:54 +01:00
b045b571a6 (v1.4.0.9025) is_new_episode() 2020-11-23 21:50:27 +01:00
363218da7e (v1.4.0.9024) is_new_episode() 2020-11-17 16:57:41 +01:00
0800d33228 (v1.4.0.9023) unit tests 2020-11-17 11:53:56 +01:00
93428415d0 (v1.4.0.9022) small bugfix 2020-11-16 20:02:20 +01:00
deefce9520 (v1.4.0.9021) more robust class setting 2020-11-16 16:57:55 +01:00
05fb213a7c (v1.4.0.9020) mo_is_intrinsic_resistant 2020-11-16 11:03:24 +01:00
9666b78ea7 (v1.4.0.9019) documentation update 2020-11-12 11:07:23 +01:00
f2edac3b67 (v1.4.0.9018) reference_data in as.rsi() 2020-11-11 18:54:03 +01:00
01d9522434 (v1.4.0.9017) stringsAsFactors definitions 2020-11-11 16:49:27 +01:00
68ac39aa7f (v1.4.0.9016) as.rsi() older R versions 2020-11-10 19:59:14 +01:00
15c732703d (v1.4.0.9015) bugfix 2020-11-10 16:35:56 +01:00
dd5a0319ef (v1.4.0.9014) bugfix 2020-11-09 15:18:36 +01:00
d3b1d33210 (v1.4.0.9013) is_gram_negative/positive update 2020-11-09 13:07:02 +01:00
423879c034 (v1.4.0.9012) reference_df fix 2020-11-05 01:11:49 +01:00
5a607abb36 (v1.4.0.9011) message formatting 2020-10-27 15:56:51 +01:00
98773aa859 (v1.4.0.9010) GH actions update 2020-10-26 15:56:15 +01:00
3d096d96c2 (v1.4.0.9009) bugfix for older R version 2020-10-26 15:53:31 +01:00
760d69a3e0 (v1.4.0.9008) like variations 2020-10-26 12:23:03 +01:00
f720c9ba0b (v1.4.0.9007) bugfix 2020-10-21 15:28:48 +02:00
8f868388ce (v1.4.0.9006) bugfix 2020-10-21 14:40:00 +02:00
9109b9dd62 (v1.4.0.9005) bugfix 2020-10-21 13:07:23 +02:00
ade9f8bafd (v1.4.0.9004) bugfix 2020-10-21 11:50:43 +02:00
2ef7dfc8a3 (v1.4.0.9003) CoNS update 2020-10-20 21:00:57 +02:00
ddae8085e1 (v1.4.0.9002) bugfix 2020-10-19 20:44:45 +02:00
4e9ccb4435 (v1.4.0.9001) is_gram_positive(), is_gram_negative(), parameter hardening 2020-10-19 17:09:19 +02:00
833a1be36d (v1.4.0.9000) more extensive unit tests 2020-10-15 09:46:41 +02:00
28e77680c5 (v1.4.0) matching score update 2020-10-08 11:16:03 +02:00
c04dc852cf (v1.3.0.9039) lifecycle updates, added excess kurtosis 2020-10-04 21:02:16 +02:00
baf510183c (v1.3.0.9038) prefinal 1.4.0 2020-10-04 19:26:43 +02:00
3136bc54aa (v1.3.0.9037) pre-release 2020-09-30 10:54:23 +02:00
ac1c78c793 (v1.3.0.9036) documentation fix 2020-09-30 10:24:53 +02:00
4e0374af29 (v1.3.0.9035) mdro() for EUCAST 3.2, examples cleanup 2020-09-29 23:35:46 +02:00
68e6e1e329 (v1.3.0.9034) eucast_rules summary fix 2020-09-29 10:40:25 +02:00
36ec8b0d81 (v1.3.0.9033) skimr fix 2020-09-28 11:00:59 +02:00
519aada54f (v1.3.0.9032) support skimr 2020-09-28 01:08:55 +02:00
22f6ceb3e4 (v1.3.0.9031) matching score update 2020-09-26 16:51:17 +02:00
050a9a04fb (v1.3.0.9030) matching score update 2020-09-26 16:26:01 +02:00
9667c2994f (v1.3.0.9029) eucast rules fix, unique() 2020-09-25 14:44:50 +02:00
1d982a82b4 (v1.3.0.9028) eucast fix 2020-09-24 12:38:13 +02:00
027215ed94 (v1.3.0.9027) unit tests 2020-09-24 00:50:23 +02:00
c19095a3d5 (v1.3.0.9026) eucast expert rules 3.2 2020-09-24 00:30:11 +02:00
a1411ddafc (v1.3.0.9025) optimalisation 2020-09-19 15:15:57 +02:00
2f0186ace2 (v1.3.0.9024) optimalisation 2020-09-19 12:57:51 +02:00
d049cce69b (v1.3.0.9023) optimalisation 2020-09-19 11:54:01 +02:00
4e40e42011 (v1.3.0.9022) mo_matching_score(), poorman update, as.rsi() fix 2020-09-18 16:05:53 +02:00
89401ede9f (v1.3.0.9021) typo 2020-09-14 20:41:19 +02:00
ab60f613aa (v1.3.0.9020) fix for uncertainty in as.mo() 2020-09-14 19:41:48 +02:00
354c606d6a (v1.3.0.9019) small fix 2020-09-14 14:08:07 +02:00
7b6dd676f7 (v1.3.0.9018) language corrections 2020-09-14 12:21:23 +02:00
0f6760d427 (v1.3.0.9017) small fix 2020-09-12 13:54:21 +02:00
3ff871afeb (v1.3.0.9016) mo_uncertainties() overhaul 2020-09-12 08:49:01 +02:00
68e9cb78e9 (v1.3.0.9015) as.mo() speedup for valid taxonomic names 2020-09-03 20:59:21 +02:00
c4b87fe241 (v1.3.0.9014) as.mo() speed improvement 2020-09-03 12:31:48 +02:00
18e52f2725 (v1.3.0.9013) data sets vignette update 2020-08-29 21:52:51 +02:00
4f72b3bfc4 (v1.3.0.9012) data sets vignette update 2020-08-29 21:41:46 +02:00
50b953b141 (v1.3.0.9011) suggests pkg update 2020-08-29 12:04:23 +02:00
74a172ef55 (v1.3.0.9010) S3 extensions without dependencies 2020-08-28 21:55:47 +02:00
81af0b001c (v1.3.0.9009) documentation update 2020-08-26 16:13:40 +02:00
9b8db57c65 (v1.3.0.9008) also tibble printing for ab 2020-08-26 15:34:12 +02:00
5e45fdcf2a (v1.3.0.9007) tibble printing 2020-08-26 11:33:54 +02:00
c8c8bb4e3a (v1.3.0.9006) website update 2020-08-21 11:40:13 +02:00
818d0441e0 (v1.3.0.9005) website update 2020-08-17 21:49:58 +02:00
dab017a50f (v1.3.0.9004) data sets, as.disk() improvement 2020-08-16 21:38:42 +02:00
e73f0e211c (v1.3.0.9003) as.rsi() speed improvement 2020-08-15 12:54:47 +02:00
08d62bb5d5 (v1.3.0.9002) intrinsic_resistant data set 2020-08-14 13:36:10 +02:00
7d16bec21f (v1.3.0.9001) website update 2020-08-10 12:46:03 +02:00
0d9602a6a9 (v1.3.0.9000) support across() in as.rsi() 2020-08-10 11:44:58 +02:00
425 changed files with 133002 additions and 11740 deletions

View File

@@ -21,6 +21,7 @@
^public$
^data-raw$
^\.lintr$
^tests/testthat/_snaps$
^vignettes/AMR.Rmd$
^vignettes/benchmarks.Rmd$
^vignettes/EUCAST.Rmd$

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
on:
@@ -27,37 +31,57 @@ on:
pull_request:
branches:
- master
schedule:
# run a schedule everyday at 3 AM.
# this is to check that all dependencies are still available (see R/zzz.R)
- cron: '0 3 * * *'
name: R-code-check
jobs:
R-code-check:
runs-on: ${{ matrix.config.os }}
continue-on-error: ${{ matrix.config.allowfail }}
name: ${{ matrix.config.os }} (${{ matrix.config.r }})
name: ${{ matrix.config.os }} (R-${{ matrix.config.r }})
strategy:
fail-fast: false
matrix:
config:
- {os: windows-latest, r: 'release'}
- {os: macOS-latest, r: 'release'}
- {os: ubuntu-16.04, r: 'release', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: windows-latest, r: 'oldrel'}
# - {os: macOS-latest, r: 'oldrel'}
# - {os: ubuntu-16.04, r: 'oldrel', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: windows-latest, r: 'devel'}
- {os: macOS-latest, r: 'devel'}
# - {os: ubuntu-16.04, r: '4.0', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: windows-latest, r: '3.6'}
# - {os: ubuntu-16.04, r: '3.5', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: ubuntu-16.04, r: '3.4', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: ubuntu-16.04, r: '3.3', rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: macOS-latest, r: 'devel', allowfail: false}
- {os: macOS-latest, r: 'release', allowfail: false}
- {os: macOS-latest, r: 'oldrel', allowfail: false}
- {os: windows-latest, r: 'devel', allowfail: false}
- {os: windows-latest, r: 'release', allowfail: false}
- {os: windows-latest, r: 'oldrel', allowfail: false}
- {os: ubuntu-20.04, r: 'devel', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: 'release', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
- {os: ubuntu-20.04, r: 'oldrel', 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: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
# - {os: ubuntu-20.04, r: '3.2', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"}
# - {os: ubuntu-20.04, r: '3.1', allowfail: true, 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-16.04, r: 'devel', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: 'release', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: 'oldrel', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '4.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '3.6', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '3.5', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '3.4', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '3.3', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: ubuntu-16.04, r: '3.2', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
# - {os: ubuntu-16.04, r: '3.1', allowfail: true, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
- {os: ubuntu-16.04, r: '3.0', allowfail: false, rspm: "https://packagemanager.rstudio.com/cran/__linux__/xenial/latest"}
env:
R_REMOTES_NO_ERRORS_FROM_WARNINGS: true
RSPM: ${{ matrix.config.rspm }}
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@v2
@@ -69,30 +93,45 @@ jobs:
- uses: r-lib/actions/setup-pandoc@master
- name: Query dependencies
if: matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2'
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
if: runner.os != 'Windows'
if: runner.os != 'Windows' && matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2'
uses: actions/cache@v1
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-
key: ${{ matrix.config.os }}-r-${{ matrix.config.r }}-3-${{ hashFiles('.github/depends.Rds') }}
restore-keys: ${{ matrix.config.os }}-r-${{ matrix.config.r }}-3-
- name: Install system dependencies
if: runner.os == 'Linux'
- name: Install Linux dependencies
if: runner.os == 'Linux' && matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2'
env:
RHUB_PLATFORM: linux-x86_64-ubuntu-gcc
run: |
Rscript -e "remotes::install_github('r-hub/sysreqs')"
sysreqs=$(Rscript -e "cat(sysreqs::sysreq_commands('DESCRIPTION'))")
sudo -s eval "$sysreqs"
- name: Install Linux dependencies on old R versions
if: matrix.config.r == '3.0' || matrix.config.r == '3.1' || matrix.config.r == '3.2'
env:
RHUB_PLATFORM: linux-x86_64-ubuntu-gcc
# 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 a quite new R version
run: |
sudo apt install -y libssl-dev pandoc pandoc-citeproc libxml2-dev libicu-dev libcurl4-openssl-dev
- name: Install dependencies
- name: Install macOS dependencies
if: matrix.config.os == 'macOS-latest' && matrix.config.r == 'devel'
run: |
brew install mariadb-connector-c
- name: Install package dependencies
if: matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2'
run: |
remotes::install_deps(dependencies = TRUE)
remotes::install_cran("rcmdcheck")
@@ -101,15 +140,26 @@ jobs:
- name: Session info
run: |
options(width = 100)
pkgs <- installed.packages()[, "Package"]
sessioninfo::session_info(pkgs, include_base = TRUE)
utils::sessionInfo()
as.data.frame(utils::installed.packages())[, "Version", drop = FALSE]
shell: Rscript {0}
- name: Check
- name: Run R CMD check
if: matrix.config.r != '3.0' && matrix.config.r != '3.1' && matrix.config.r != '3.2'
env:
_R_CHECK_CRAN_INCOMING_: false
run: rcmdcheck::rcmdcheck(args = c("--no-manual", "--as-cran"), error_on = "warning", check_dir = "check")
shell: Rscript {0}
- name: Run R CMD check on older R versions
if: matrix.config.r == '3.0' || matrix.config.r == '3.1' || matrix.config.r == '3.2'
env:
_R_CHECK_CRAN_INCOMING_: false
_R_CHECK_FORCE_SUGGESTS_: false
_R_CHECK_LENGTH_1_CONDITION_: verbose
_R_CHECK_LENGTH_1_LOGIC2_: verbose
run: |
R CMD check data-raw/AMR_*.tar.gz --no-manual --no-build-vignettes
- name: Show testthat output
if: always()
@@ -118,7 +168,7 @@ jobs:
- name: Upload check results
if: failure()
uses: actions/upload-artifact@main
uses: actions/upload-artifact@master
with:
name: ${{ runner.os }}-r${{ matrix.config.r }}-results
name: ${{ matrix.config.os }}-r${{ matrix.config.r }}-results
path: check

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
on:
@@ -63,5 +67,5 @@ jobs:
shell: Rscript {0}
- name: Test coverage
run: covr::codecov(line_exclusions = list("R/atc_online.R", "R/mo_source.R", "R/resistance_predict.R", "R/aa_helper_functions_dplyr.R"))
run: 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"), quiet = FALSE)
shell: Rscript {0}

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# 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 more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
on:
@@ -26,7 +30,6 @@ on:
- master
pull_request:
branches:
- premaster
- master
name: lintr
@@ -63,5 +66,5 @@ jobs:
shell: Rscript {0}
- 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_usage_linter = NULL, object_length_linter = lintr::object_length_linter(length = 50L)), exclusions = list("R/aa_helper_functions_dplyr.R"))
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"))
shell: Rscript {0}

1
.gitignore vendored
View File

@@ -24,3 +24,4 @@ data-raw/taxa.txt
data-raw/taxon.tab
data-raw/DSMZ_bactnames.xlsx
data-raw/country_analysis_url_token.R
data-raw/country_analysis2.R

View File

@@ -1,6 +1,6 @@
Package: AMR
Version: 1.3.0
Date: 2020-07-31
Version: 1.5.0.9009
Date: 2021-01-22
Title: Antimicrobial Resistance Analysis
Authors@R: c(
person(role = c("aut", "cre"),
@@ -21,6 +21,8 @@ Authors@R: c(
family = "Hassing", given = c("Erwin", "E.", "A."), email = "e.hassing@certe.nl"),
person(role = "ctb",
family = "Hazenberg", given = c("Eric", "H.", "L.", "C.", "M."), email = "e.hazenberg@jbz.nl"),
person(role = "ctb",
family = "Knight", given = "Gwen", email = "gwen.knight@lshtm.ac.uk"),
person(role = "ctb",
family = "Lenglet", given = "Annick", email = "annick.lenglet@amsterdam.msf.org"),
person(role = "ctb",
@@ -28,7 +30,11 @@ Authors@R: c(
person(role = "ctb",
family = "Ny", given = "Sofia", email = "sofia.ny@folkhalsomyndigheten.se"),
person(role = "ctb",
family = "Souverein", given = "Dennis", email = "d.souvereing@streeklabhaarlem.nl"))
family = "Schade", given = c("Rogier", "P."), email = "r.schade@amsterdamumc.nl"),
person(role = "ctb",
family = "Souverein", given = "Dennis", email = "d.souvereing@streeklabhaarlem.nl"),
person(role = "ctb",
family = "Underwood", given = "Anthony", email = "au3@sanger.ac.uk"))
Description: Functions to simplify the analysis and prediction of Antimicrobial
Resistance (AMR) and to work with microbial and antimicrobial properties by
using evidence-based methods, like those defined by Leclercq et al. (2013)
@@ -38,16 +44,22 @@ Depends:
R (>= 3.0.0)
Suggests:
cleaner,
curl,
dplyr,
ggplot2,
knitr,
microbenchmark,
pillar,
readxl,
rmarkdown,
rstudioapi,
rvest,
skimr,
testthat,
tidyr,
utils
xml2
VignetteBuilder: knitr,rmarkdown
URL: https://msberends.github.io/AMR, https://github.com/msberends/AMR
URL: https://msberends.github.io/AMR/, https://github.com/msberends/AMR
BugReports: https://github.com/msberends/AMR/issues
License: GPL-2 | file LICENSE
Encoding: UTF-8

View File

@@ -2,22 +2,27 @@
S3method("[",ab)
S3method("[",disk)
S3method("[",isolate_identifier)
S3method("[",mic)
S3method("[",mo)
S3method("[<-",ab)
S3method("[<-",disk)
S3method("[<-",isolate_identifier)
S3method("[<-",mic)
S3method("[<-",mo)
S3method("[<-",rsi)
S3method("[[",ab)
S3method("[[",disk)
S3method("[[",isolate_identifier)
S3method("[[",mic)
S3method("[[",mo)
S3method("[[<-",ab)
S3method("[[<-",disk)
S3method("[[<-",isolate_identifier)
S3method("[[<-",mic)
S3method("[[<-",mo)
S3method("[[<-",rsi)
S3method(all.equal,isolate_identifier)
S3method(as.data.frame,ab)
S3method(as.data.frame,mo)
S3method(as.double,mic)
@@ -31,6 +36,7 @@ S3method(barplot,mic)
S3method(barplot,rsi)
S3method(c,ab)
S3method(c,disk)
S3method(c,isolate_identifier)
S3method(c,mic)
S3method(c,mo)
S3method(c,rsi)
@@ -40,13 +46,16 @@ S3method(format,bug_drug_combinations)
S3method(kurtosis,data.frame)
S3method(kurtosis,default)
S3method(kurtosis,matrix)
S3method(plot,disk)
S3method(plot,mic)
S3method(plot,resistance_predict)
S3method(plot,rsi)
S3method(print,ab)
S3method(print,bug_drug_combinations)
S3method(print,catalogue_of_life_version)
S3method(print,custom_mdro_guideline)
S3method(print,disk)
S3method(print,isolate_identifier)
S3method(print,mic)
S3method(print,mo)
S3method(print,mo_renamed)
@@ -58,6 +67,12 @@ S3method(skewness,matrix)
S3method(summary,mic)
S3method(summary,mo)
S3method(summary,rsi)
S3method(unique,ab)
S3method(unique,disk)
S3method(unique,isolate_identifier)
S3method(unique,mic)
S3method(unique,mo)
S3method(unique,rsi)
export("%like%")
export("%like_case%")
export(ab_atc)
@@ -107,6 +122,8 @@ export(count_all)
export(count_df)
export(count_resistant)
export(count_susceptible)
export(custom_mdro_guideline)
export(eucast_dosage)
export(eucast_exceptional_phenotypes)
export(eucast_rules)
export(facet_rsi)
@@ -131,6 +148,7 @@ export(fluoroquinolones)
export(full_join_microorganisms)
export(g.test)
export(geom_rsi)
export(get_episode)
export(get_locale)
export(get_mo_source)
export(ggplot_pca)
@@ -145,6 +163,8 @@ export(is.mic)
export(is.mo)
export(is.rsi)
export(is.rsi.eligible)
export(is_new_episode)
export(isolate_identifier)
export(key_antibiotics)
export(key_antibiotics_equal)
export(kurtosis)
@@ -164,7 +184,12 @@ export(mo_fullname)
export(mo_genus)
export(mo_gramstain)
export(mo_info)
export(mo_is_gram_negative)
export(mo_is_gram_positive)
export(mo_is_intrinsic_resistant)
export(mo_is_yeast)
export(mo_kingdom)
export(mo_matching_score)
export(mo_name)
export(mo_order)
export(mo_phylum)
@@ -187,18 +212,15 @@ export(n_rsi)
export(p_symbol)
export(pca)
export(penicillins)
export(portion_I)
export(portion_IR)
export(portion_R)
export(portion_S)
export(portion_SI)
export(portion_df)
export(proportion_I)
export(proportion_IR)
export(proportion_R)
export(proportion_S)
export(proportion_SI)
export(proportion_df)
export(random_disk)
export(random_mic)
export(random_rsi)
export(resistance)
export(resistance_predict)
export(right_join_microorganisms)
@@ -216,6 +238,7 @@ importFrom(graphics,arrows)
importFrom(graphics,axis)
importFrom(graphics,barplot)
importFrom(graphics,par)
importFrom(graphics,plot)
importFrom(graphics,points)
importFrom(graphics,text)
importFrom(stats,complete.cases)

296
NEWS.md
View File

@@ -1,5 +1,195 @@
# AMR 1.3.0
# AMR 1.5.0.9009
## <small>Last updated: 22 January 2021</small>
### New
* Support for EUCAST Clinical Breakpoints v11.0 (2021), effective in the `eucast_rules()` function and in `as.rsi()` to interpret MIC and disk diffusion values. This is now the default guideline in this package.
* Data set `dosage` to fuel the new `eucast_dosage()` function and to make this data available in a structured way
* Function `eucast_dosage()` to get a `data.frame` with advised dosages of a certain bug-drug combination, which is based on the new `dosage` data set
* Support for custom MDRO guidelines, using the new `custom_mdro_guideline()` function, please see `mdro()` for additional info
* Function `isolate_identifier()`, which will paste a microorganism code with all antimicrobial results of a data set into one string for each row. This is useful to compare isolates, e.g. between institutions or regions, when there is no genotyping available.
* Function `mo_is_yeast()`, which determines whether a microorganism is a member of the taxonomic class Saccharomycetes or the taxonomic order Saccharomycetales:
```r
mo_kingdom(c("Aspergillus", "Candida"))
#> [1] "Fungi" "Fungi"
mo_is_yeast(c("Aspergillus", "Candida"))
#> [1] FALSE TRUE
# usage for filtering data:
example_isolates[which(mo_is_yeast()), ] # base R
example_isolates %>% filter(mo_is_yeast()) # dplyr
```
The `mo_type()` function has also been updated to reflect this change:
```r
mo_type(c("Aspergillus", "Candida"))
# [1] "Fungi" "Yeasts"
mo_type(c("Aspergillus", "Candida"), language = "es") # also supported: de, nl, fr, it, pt
#> [1] "Hongos" "Levaduras"
```
### Changed
* Using functions without setting a data set (e.g., `mo_is_gram_negative()`, `mo_is_gram_positive()`, `mo_is_intrinsic_resistant()`, `first_isolate()`, `mdro()`) now work with `dplyr`s `group_by()` again
* Updated the data set `microorganisms.codes` (which contains popular LIS and WHONET codes for microorganisms) for some species of *Mycobacterium* that previously incorrectly returned *M. africanum*
* Added Pretomanid (PMD, J04AK08) to the `antibiotics` data set
* WHONET code `"PNV"` will now correctly be interpreted as `PHN`, the antibiotic code for phenoxymethylpenicillin ('peni V')
* Fix for verbose output of `mdro(..., verbose = TRUE)` for German guideline (3MGRN and 4MGRN) and Dutch guideline (BRMO, only *P. aeruginosa*)
* `is.rsi.eligible()` now returns `FALSE` immediately if the input does not contain any of the values "R", "S" or "I". This drastically improves speed, also for a lot of other functions that rely on automatic determination of antibiotic columns.
### Other
* Big documentation updates
* Loading the package (i.e., `library(AMR)`) now is ~50 times faster than before
# AMR 1.5.0
### New
* Functions `get_episode()` and `is_new_episode()` to determine (patient) episodes which are not necessarily based on microorganisms. The `get_episode()` function returns the index number of the episode per group, while the `is_new_episode()` function returns values `TRUE`/`FALSE` to indicate whether an item in a vector is the start of a new episode. They also support `dplyr`s grouping (i.e. using `group_by()`):
```r
library(dplyr)
example_isolates %>%
group_by(patient_id, hospital_id) %>%
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.
* Function `mo_is_intrinsic_resistant()` to test for intrinsic resistance, based on [EUCAST Intrinsic Resistance and Unusual Phenotypes v3.2](https://www.eucast.org/expert_rules_and_intrinsic_resistance/) from 2020.
* Functions `random_mic()`, `random_disk()` and `random_rsi()` for random value generation. The functions `random_mic()` and `random_disk()` take microorganism names and antibiotic names as input to make generation more realistic.
### Changed
* New argument `ampc_cephalosporin_resistance` in `eucast_rules()` to correct for AmpC de-repressed cephalosporin-resistant mutants
* Interpretation of antimicrobial resistance - `as.rsi()`:
* Reference data used for `as.rsi()` can now be set by the user, using the `reference_data` argument. This allows for using own interpretation guidelines. The user-set data must have the same structure as `rsi_translation`.
* Better determination of disk zones and MIC values when running `as.rsi()` on a data.frame
* Fix for using `as.rsi()` on a data.frame in older R versions
* `as.rsi()` on a data.frame will not print a message anymore if the values are already clean R/SI values
* If using `as.rsi()` on MICs or disk diffusion while there is intrinsic antimicrobial resistance, a warning will be thrown to remind about this
* Fix for using `as.rsi()` on a `data.frame` that only contains one column for antibiotic interpretations
* Some functions are now context-aware when used inside `dplyr` verbs, such as `filter()`, `mutate()` and `summarise()`. This means that then the data argument does not need to be set anymore. This is the case for the new functions:
* `mo_is_gram_negative()`
* `mo_is_gram_positive()`
* `mo_is_intrinsic_resistant()`
... and for the existing functions:
* `first_isolate()`,
* `key_antibiotics()`,
* `mdro()`,
* `brmo()`,
* `mrgn()`,
* `mdr_tb()`,
* `mdr_cmi2012()`,
* `eucast_exceptional_phenotypes()`
```r
# to select first isolates that are Gram-negative
# and view results of cephalosporins and aminoglycosides:
library(dplyr)
example_isolates %>%
filter(first_isolate(), mo_is_gram_negative()) %>%
select(mo, cephalosporins(), aminoglycosides()) %>%
as_tibble()
```
* For antibiotic selection functions (such as `cephalosporins()`, `aminoglycosides()`) to select columns based on a certain antibiotic group, the dependency on the `tidyselect` package was removed, meaning that they can now also be used without the need to have this package installed and now also work in base R function calls (they rely on R 3.2 or later):
```r
# above example in base R:
example_isolates[which(first_isolate() & mo_is_gram_negative()),
c("mo", cephalosporins(), aminoglycosides())]
```
* For all function arguments in the code, it is now defined what the exact type of user input should be (inspired by the [`typed`](https://github.com/moodymudskipper/typed) package). If the user input for a certain function does not meet the requirements for a specific argument (such as the class or length), an informative error will be thrown. This makes the package more robust and the use of it more reproducible and reliable. In total, more than 420 arguments were defined.
* Fix for `set_mo_source()`, that previously would not remember the file location of the original file
* Deprecated function `p_symbol()` that not really fits the scope of this package. It will be removed in a future version. See [here](https://github.com/msberends/AMR/blob/v1.4.0/R/p_symbol.R) for the source code to preserve it.
* Updated coagulase-negative staphylococci determination with Becker *et al.* 2020 (PMID 32056452), meaning that the species *S. argensis*, *S. caeli*, *S. debuckii*, *S. edaphicus* and *S. pseudoxylosus* are now all considered CoNS
* Fix for using argument `reference_df` in `as.mo()` and `mo_*()` functions that contain old microbial codes (from previous package versions)
* Fixed a bug where `mo_uncertainties()` would not return the results based on the MO matching score
* Fixed a bug where `as.mo()` would not return results for known laboratory codes for microorganisms
* Fixed a bug where `as.ab()` would sometimes fail
* Better tibble printing for MIC values
* Fix for plotting MIC values with `plot()`
* Added `plot()` generic to class `<disk>`
* LA-MRSA and CA-MRSA are now recognised as an abbreviation for *Staphylococcus aureus*, meaning that e.g. `mo_genus("LA-MRSA")` will return `"Staphylococcus"` and `mo_is_gram_positive("LA-MRSA")` will return `TRUE`.
* Fix for printing class <mo> in tibbles when all values are `NA`
* Fix for `mo_shortname()` when the input contains `NA`
* If `as.mo()` takes more than 30 seconds, some suggestions will be done to improve speed
### Other
* All messages and warnings thrown by this package now break sentences on whole words
* More extensive unit tests
* Internal calls to `options()` were all removed in favour of a new internal environment `pkg_env`
* Improved internal type setting (among other things: replaced all `sapply()` calls with `vapply()`)
* Added CodeFactor as a continuous code review to this package: <https://www.codefactor.io/repository/github/msberends/amr/>
* Added Dr. Rogier Schade as contributor
# AMR 1.4.0
### New
* Support for 'EUCAST Expert Rules' / 'EUCAST Intrinsic Resistance and Unusual Phenotypes' version 3.2 of May 2020. With this addition to the previously implemented version 3.1 of 2016, the `eucast_rules()` function can now correct for more than 180 different antibiotics and the `mdro()` function can determine multidrug resistance based on more than 150 different antibiotics. All previously implemented versions of the EUCAST rules are now maintained and kept available in this package. The `eucast_rules()` function consequently gained the arguments `version_breakpoints` (at the moment defaults to v10.0, 2020) and `version_expertrules` (at the moment defaults to v3.2, 2020). The `example_isolates` data set now also reflects the change from v3.1 to v3.2. The `mdro()` function now accepts `guideline == "EUCAST3.1"` and `guideline == "EUCAST3.2"`.
* A new vignette and website page with info about all our public and freely available data sets, that can be downloaded as flat files or in formats for use in R, SPSS, SAS, Stata and Excel: https://msberends.github.io/AMR/articles/datasets.html
* Data set `intrinsic_resistant`. This data set contains all bug-drug combinations where the 'bug' is intrinsic resistant to the 'drug' according to the latest EUCAST insights. It contains just two columns: `microorganism` and `antibiotic`.
Curious about which enterococci are actually intrinsic resistant to vancomycin?
```r
library(AMR)
library(dplyr)
intrinsic_resistant %>%
filter(antibiotic == "Vancomycin", microorganism %like% "Enterococcus") %>%
pull(microorganism)
#> [1] "Enterococcus casseliflavus" "Enterococcus gallinarum"
```
* Support for veterinary ATC codes
* Support for skimming classes `<rsi>`, `<mic>`, `<disk>` and `<mo>` with the `skimr` package
### Changed
* Although advertised that this package should work under R 3.0.0, we still had a dependency on R 3.6.0. This is fixed, meaning that our package should now work under R 3.0.0.
* Improvements for `as.rsi()`:
* Support for using `dplyr`'s `across()` to interpret MIC values or disk zone diameters, which also automatically determines the column with microorganism names or codes.
```r
# until dplyr 1.0.0
your_data %>% mutate_if(is.mic, as.rsi)
your_data %>% mutate_if(is.disk, as.rsi)
# since dplyr 1.0.0
your_data %>% mutate(across(where(is.mic), as.rsi))
your_data %>% mutate(across(where(is.disk), as.rsi))
```
* Cleaning columns in a data.frame now allows you to specify those columns with tidy selection, e.g. `as.rsi(df, col1:col9)`
* Big speed improvement for interpreting MIC values and disk zone diameters. When interpreting 5,000 MIC values of two antibiotics (10,000 values in total), our benchmarks showed a total run time going from 80.7-85.1 seconds to 1.8-2.0 seconds.
* Added argument 'add_intrinsic_resistance' (defaults to `FALSE`), that considers intrinsic resistance according to EUCAST
* Fixed a bug where in EUCAST rules the breakpoint for R would be interpreted as ">=" while this should have been "<"
* Added intelligent data cleaning to `as.disk()`, so numbers can also be extracted from text and decimal numbers will always be rounded up:
```r
as.disk(c("disk zone: 23.4 mm", 23.4))
#> Class <disk>
#> [1] 24 24
```
* Improvements for `as.mo()`:
* A completely new matching score for ambiguous user input, using `mo_matching_score()`. Any user input value that could mean more than one taxonomic entry is now considered 'uncertain'. Instead of a warning, a message will be thrown and the accompanying `mo_uncertainties()` has been changed completely; it now prints all possible candidates with their matching score.
* Big speed improvement for already valid microorganism ID. This also means an significant speed improvement for using `mo_*` functions like `mo_name()` on microoganism IDs.
* Added argument `ignore_pattern` to `as.mo()` which can also be given to `mo_*` functions like `mo_name()`, to exclude known non-relevant input from analysing. This can also be set with the option `AMR_ignore_pattern`.
* `get_locale()` now uses at default `Sys.getenv("LANG")` or, if `LANG` is not set, `Sys.getlocale()`. This can be overwritten by setting the option `AMR_locale`.
* Big speed improvement for `eucast_rules()`
* Overall speed improvement by tweaking joining functions
* Function `mo_shortname()` now returns the genus for input where the species is unknown
* BORSA is now recognised as an abbreviation for *Staphylococcus aureus*, meaning that e.g. `mo_genus("BORSA")` will return "Staphylococcus"
* Added a feature from AMR 1.1.0 and earlier again, but now without other package dependencies: `tibble` printing support for classes `<rsi>`, `<mic>`, `<disk>`, `<ab>` and `<mo>`. When using `tibble`s containing antimicrobial columns (class `<rsi>`), "S" will print in green, "I" will print in yellow and "R" will print in red. Microbial IDs (class `<mo>`) will emphasise on the genus and species, not on the kingdom.
* Names of antiviral agents in data set `antivirals` now have a starting capital letter, like it is the case in the `antibiotics` data set
* Updated the documentation of the `WHONET` data set to clarify that all patient names are fictitious
* Small `as.ab()` algorithm improvements
* Fix for combining MIC values with raw numbers, i.e. `c(as.mic(2), 2)` previously failed but now returns a valid MIC class
* `ggplot_rsi()` and `geom_rsi()` gained arguments `minimum` and `language`, to influence the internal use of `rsi_df()`
* Changes in the `antibiotics` data set:
* Updated oral and parental DDDs from the WHOCC
* Added abbreviation "piptazo" to 'Piperacillin/tazobactam' (TZP)
* 'Penicillin G' (for intravenous use) is now named 'Benzylpenicillin' (code `PEN`)
* 'Penicillin V' (for oral use, code `PNV`) was removed, since its actual entry 'Phenoxymethylpenicillin' (code `PHN`) already existed
* The group name (`antibiotics$group`) of 'Linezolid' (`LNZ`), 'Cycloserine' (`CYC`), 'Tedizolid' (`TZD`) and 'Thiacetazone' (`THA`) is now "Oxazolidinones" instead of "Other antibacterials"
* Added support for using `unique()` on classes `<rsi>`, `<mic>`, `<disk>`, `<ab>` and `<mo>`
* Added argument `excess` to the `kurtosis()` function (defaults to `FALSE`), to return the *excess kurtosis*, defined as the kurtosis minus three.
### Other
* Removed functions `portion_R()`, `portion_S()` and `portion_I()` that were deprecated since version 0.9.0 (November 2019) and were replaced with `proportion_R()`, `proportion_S()` and `proportion_I()`
* Removed unnecessary references to the `base` package
* Added packages that could be useful for some functions to the `Suggests` field of the `DESCRIPTION` file
# AMR 1.3.0
### New
* Function `ab_from_text()` to retrieve antimicrobial drug names, doses and forms of administration from clinical texts in e.g. health care records, which also corrects for misspelling since it uses `as.ab()` internally
@@ -17,7 +207,7 @@
* Added official antimicrobial names to all `filter_ab_class()` functions, such as `filter_aminoglycosides()`
* Added antibiotics code "FOX1" for cefoxitin screening (abbreviation "cfsc") to the `antibiotics` data set
* Added Monuril as trade name for fosfomycin
* Added parameter `conserve_capped_values` to `as.rsi()` for interpreting MIC values - it makes sure that values starting with "<" (but not "<=") will always return "S" and values starting with ">" (but not ">=") will always return "R". The default behaviour of `as.rsi()` has not changed, so you need to specifically do `as.rsi(..., conserve_capped_values = TRUE)`.
* Added argument `conserve_capped_values` to `as.rsi()` for interpreting MIC values - it makes sure that values starting with "<" (but not "<=") will always return "S" and values starting with ">" (but not ">=") will always return "R". The default behaviour of `as.rsi()` has not changed, so you need to specifically do `as.rsi(..., conserve_capped_values = TRUE)`.
### Changed
* Big speed improvement for using any function on microorganism codes from earlier package versions (prior to `AMR` v1.2.0), such as `as.mo()`, `mo_name()`, `first_isolate()`, `eucast_rules()`, `mdro()`, etc.
@@ -61,8 +251,8 @@
Negative effects of this change are:
* Function `freq()` that was borrowed from the `cleaner` package was removed. Use `cleaner::freq()`, or run `library("cleaner")` before you use `freq()`.
* Printing values of class `mo` or `rsi` in a tibble will no longer be in colour and printing `rsi` in a tibble will show the class `<ord>`, not `<rsi>` anymore. This is purely a visual effect.
* All functions from the `mo_*` family (like `mo_name()` and `mo_gramstain()`) are noticeably slower when running on hundreds of thousands of rows.
* ~~Printing values of class `mo` or `rsi` in a tibble will no longer be in colour and printing `rsi` in a tibble will show the class `<ord>`, not `<rsi>` anymore. This is purely a visual effect.~~
* ~~All functions from the `mo_*` family (like `mo_name()` and `mo_gramstain()`) are noticeably slower when running on hundreds of thousands of rows.~~
* For developers: classes `mo` and `ab` now both also inherit class `character`, to support any data transformation. This change invalidates code that checks for class length == 1.
### Changed
@@ -125,7 +315,7 @@
mutate_at(vars(antibiotic1:antibiotic25), as.rsi, mo = .$mybacteria)
```
* Added antibiotic abbreviations for a laboratory manufacturer (GLIMS) for cefuroxime, cefotaxime, ceftazidime, cefepime, cefoxitin and trimethoprim/sulfamethoxazole
* Added `uti` (as abbreviation of urinary tract infections) as parameter to `as.rsi()`, so interpretation of MIC values and disk zones can be made dependent on isolates specifically from UTIs
* Added `uti` (as abbreviation of urinary tract infections) as argument to `as.rsi()`, so interpretation of MIC values and disk zones can be made dependent on isolates specifically from UTIs
* Info printing in functions `eucast_rules()`, `first_isolate()`, `mdro()` and `resistance_predict()` will now at default only print when R is in an interactive mode (i.e. not in RMarkdown)
# AMR 1.0.0
@@ -133,7 +323,7 @@
This software is now out of beta and considered stable. Nonetheless, this package will be developed continually.
### New
* Support for the newest [EUCAST Clinical Breakpoint Tables v.10.0](http://www.eucast.org/clinical_breakpoints/), valid from 1 January 2020. This affects translation of MIC and disk zones using `as.rsi()` and inferred resistance and susceptibility using `eucast_rules()`.
* Support for the newest [EUCAST Clinical Breakpoint Tables v.10.0](https://www.eucast.org/clinical_breakpoints/), valid from 1 January 2020. This affects translation of MIC and disk zones using `as.rsi()` and inferred resistance and susceptibility using `eucast_rules()`.
* The repository of this package now contains a clean version of the EUCAST and CLSI guidelines from 2011-2020 to translate MIC and disk diffusion values to R/SI: <https://github.com/msberends/AMR/blob/master/data-raw/rsi_translation.txt>. This **allows for machine reading these guidelines**, which is almost impossible with the Excel and PDF files distributed by EUCAST and CLSI. This file used to process the EUCAST Clinical Breakpoints Excel file [can be found here](https://github.com/msberends/AMR/blob/master/data-raw/read_EUCAST.R).
* Support for LOINC and SNOMED codes
* Support for LOINC codes in the `antibiotics` data set. Use `ab_loinc()` to retrieve LOINC codes, or use a LOINC code for input in any `ab_*` function:
@@ -179,7 +369,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
# AMR 0.9.0
### Breaking
* Adopted Adeolu *et al.* (2016), [PMID 27620848](https://www.ncbi.nlm.nih.gov/pubmed/27620848) for the `microorganisms` data set, which means that the new order Enterobacterales now consists of a part of the existing family Enterobacteriaceae, but that this family has been split into other families as well (like *Morganellaceae* and *Yersiniaceae*). Although published in 2016, this information is not yet in the Catalogue of Life version of 2019. All MDRO determinations with `mdro()` will now use the Enterobacterales order for all guidelines before 2016 that were dependent on the Enterobacteriaceae family.
* Adopted Adeolu *et al.* (2016), [PMID 27620848](https:/pubmed.ncbi.nlm.nih.gov/27620848/) for the `microorganisms` data set, which means that the new order Enterobacterales now consists of a part of the existing family Enterobacteriaceae, but that this family has been split into other families as well (like *Morganellaceae* and *Yersiniaceae*). Although published in 2016, this information is not yet in the Catalogue of Life version of 2019. All MDRO determinations with `mdro()` will now use the Enterobacterales order for all guidelines before 2016 that were dependent on the Enterobacteriaceae family.
* If you were dependent on the old Enterobacteriaceae family e.g. by using in your code:
```r
if (mo_family(somebugs) == "Enterobacteriaceae") ...
@@ -245,7 +435,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
# AMR 0.8.0
### Breaking
* Determination of first isolates now **excludes** all 'unknown' microorganisms at default, i.e. microbial code `"UNKNOWN"`. They can be included with the new parameter `include_unknown`:
* Determination of first isolates now **excludes** all 'unknown' microorganisms at default, i.e. microbial code `"UNKNOWN"`. They can be included with the new argument `include_unknown`:
```r
first_isolate(..., include_unknown = TRUE)
```
@@ -296,7 +486,7 @@ This software is now out of beta and considered stable. Nonetheless, this packag
```r
format(x, combine_IR = FALSE)
```
* Additional way to calculate co-resistance, i.e. when using multiple antimicrobials as input for `portion_*` functions or `count_*` functions. This can be used to determine the empiric susceptibility of a combination therapy. A new parameter `only_all_tested` (**which defaults to `FALSE`**) replaces the old `also_single_tested` and can be used to select one of the two methods to count isolates and calculate portions. The difference can be seen in this example table (which is also on the `portion` and `count` help pages), where the %SI is being determined:
* Additional way to calculate co-resistance, i.e. when using multiple antimicrobials as input for `portion_*` functions or `count_*` functions. This can be used to determine the empiric susceptibility of a combination therapy. A new argument `only_all_tested` (**which defaults to `FALSE`**) replaces the old `also_single_tested` and can be used to select one of the two methods to count isolates and calculate portions. The difference can be seen in this example table (which is also on the `portion` and `count` help pages), where the %SI is being determined:
```r
# --------------------------------------------------------------------
@@ -352,13 +542,13 @@ This software is now out of beta and considered stable. Nonetheless, this packag
* Removed deprecated functions `abname()`, `ab_official()`, `atc_name()`, `atc_official()`, `atc_property()`, `atc_tradenames()`, `atc_trivial_nl()`
* Fix and speed improvement for `mo_shortname()`
* Fix for using `mo_*` functions where the coercion uncertainties and failures would not be available through `mo_uncertainties()` and `mo_failures()` anymore
* Deprecated the `country` parameter of `mdro()` in favour of the already existing `guideline` parameter to support multiple guidelines within one country
* Deprecated the `country` argument of `mdro()` in favour of the already existing `guideline` argument to support multiple guidelines within one country
* The `name` of `RIF` is now Rifampicin instead of Rifampin
* The `antibiotics` data set is now sorted by name and all cephalosporins now have their generation between brackets
* Speed improvement for `guess_ab_col()` which is now 30 times faster for antibiotic abbreviations
* Improved `filter_ab_class()` to be more reliable and to support 5th generation cephalosporins
* Function `availability()` now uses `portion_R()` instead of `portion_IR()`, to comply with EUCAST insights
* Functions `age()` and `age_groups()` now have a `na.rm` parameter to remove empty values
* Functions `age()` and `age_groups()` now have a `na.rm` argument to remove empty values
* Renamed function `p.symbol()` to `p_symbol()` (the former is now deprecated and will be removed in a future version)
* Using negative values for `x` in `age_groups()` will now introduce `NA`s and not return an error anymore
* Fix for determining the system's language
@@ -453,12 +643,12 @@ This software is now out of beta and considered stable. Nonetheless, this packag
* All `atc_*` functions are superceded by `ab_*` functions
* All output will be translated by using an included translation file which [can be viewed here](https://github.com/msberends/AMR/blob/master/data-raw/translations.tsv)
* Improvements to plotting AMR results with `ggplot_rsi()`:
* New parameter `colours` to set the bar colours
* New parameters `title`, `subtitle`, `caption`, `x.title` and `y.title` to set titles and axis descriptions
* New argument `colours` to set the bar colours
* New arguments `title`, `subtitle`, `caption`, `x.title` and `y.title` to set titles and axis descriptions
* Improved intelligence of looking up antibiotic columns in a data set using `guess_ab_col()`
* Added ~5,000 more old taxonomic names to the `microorganisms.old` data set, which leads to better results finding when using the `as.mo()` function
* This package now honours the new EUCAST insight (2019) that S and I are but classified as susceptible, where I is defined as 'increased exposure' and not 'intermediate' anymore. For functions like `portion_df()` and `count_df()` this means that their new parameter `combine_SI` is TRUE at default. Our plotting function `ggplot_rsi()` also reflects this change since it uses `count_df()` internally.
* The `age()` function gained a new parameter `exact` to determine ages with decimals
* This package now honours the new EUCAST insight (2019) that S and I are but classified as susceptible, where I is defined as 'increased exposure' and not 'intermediate' anymore. For functions like `portion_df()` and `count_df()` this means that their new argument `combine_SI` is TRUE at default. Our plotting function `ggplot_rsi()` also reflects this change since it uses `count_df()` internally.
* The `age()` function gained a new argument `exact` to determine ages with decimals
* Removed deprecated functions `guess_mo()`, `guess_atc()`, `EUCAST_rules()`, `interpretive_reading()`, `rsi()`
* Frequency tables (`freq()`):
* speed improvement for microbial IDs
@@ -502,11 +692,11 @@ This software is now out of beta and considered stable. Nonetheless, this packag
We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.gitlab.io/AMR/) (built with the great [`pkgdown`](https://pkgdown.r-lib.org/))
* Contains the complete manual of this package and all of its functions with an explanation of their parameters
* Contains the complete manual of this package and all of its functions with an explanation of their arguments
* Contains a comprehensive tutorial about how to conduct antimicrobial resistance analysis, import data from WHONET or SPSS and many more.
#### New
* **BREAKING**: removed deprecated functions, parameters and references to 'bactid'. Use `as.mo()` to identify an MO code.
* **BREAKING**: removed deprecated functions, arguments and references to 'bactid'. Use `as.mo()` to identify an MO code.
* Catalogue of Life as a new taxonomic source for data about microorganisms, which also contains all ITIS data we used previously. The `microorganisms` data set now contains:
* All ~55,000 (sub)species from the kingdoms of Archaea, Bacteria and Protozoa
* All ~3,000 (sub)species from these orders of the kingdom of Fungi: Eurotiales, Onygenales, Pneumocystales, Saccharomycetales and Schizosaccharomycetales (covering at least like all species of *Aspergillus*, *Candida*, *Pneumocystis*, *Saccharomyces* and *Trichophyton*)
@@ -518,8 +708,8 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Due to this change, some `mo` codes changed (e.g. *Streptococcus* changed from `B_STRPTC` to `B_STRPT`). A translation table is used internally to support older microorganism IDs, so users will not notice this difference.
* New function `mo_rank()` for the taxonomic rank (genus, species, infraspecies, etc.)
* New function `mo_url()` to get the direct URL of a species from the Catalogue of Life
* Support for data from [WHONET](https://whonet.org/) and [EARS-Net](https://ecdc.europa.eu/en/about-us/partnerships-and-networks/disease-and-laboratory-networks/ears-net) (European Antimicrobial Resistance Surveillance Network):
* Exported files from WHONET can be read and used in this package. For functions like `first_isolate()` and `eucast_rules()`, all parameters will be filled in automatically.
* Support for data from [WHONET](https://whonet.org/) and [EARS-Net](https://www.ecdc.europa.eu/en/about-us/partnerships-and-networks/disease-and-laboratory-networks/ears-net) (European Antimicrobial Resistance Surveillance Network):
* Exported files from WHONET can be read and used in this package. For functions like `first_isolate()` and `eucast_rules()`, all arguments will be filled in automatically.
* This package now knows all antibiotic abbrevations by EARS-Net (which are also being used by WHONET) - the `antibiotics` data set now contains a column `ears_net`.
* The function `as.mo()` now knows all WHONET species abbreviations too, because almost 2,000 microbial abbreviations were added to the `microorganisms.codes` data set.
* New filters for antimicrobial classes. Use these functions to filter isolates on results in one of more antibiotics from a specific class:
@@ -587,7 +777,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
#### Changed
* Function `eucast_rules()`:
* Updated EUCAST Clinical breakpoints to [version 9.0 of 1 January 2019](http://www.eucast.org/clinical_breakpoints/), the data set `septic_patients` now reflects these changes
* Updated EUCAST Clinical breakpoints to [version 9.0 of 1 January 2019](https://www.eucast.org/clinical_breakpoints/), the data set `septic_patients` now reflects these changes
* Fixed a critical bug where some rules that depend on previous applied rules would not be applied adequately
* Emphasised in manual that penicillin is meant as benzylpenicillin (ATC [J01CE01](https://www.whocc.no/atc_ddd_index/?code=J01CE01))
* New info is returned when running this function, stating exactly what has been changed or added. Use `eucast_rules(..., verbose = TRUE)` to get a data set with all changed per bug and drug combination.
@@ -640,14 +830,14 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Console will return the percentage of uncoercable input
* Function `first_isolate()`:
* Fixed a bug where distances between dates would not be calculated right - in the `septic_patients` data set this yielded a difference of 0.15% more isolates
* Will now use a column named like "patid" for the patient ID (parameter `col_patientid`), when this parameter was left blank
* Will now use a column named like "key(...)ab" or "key(...)antibiotics" for the key antibiotics (parameter `col_keyantibiotics()`), when this parameter was left blank
* Removed parameter `output_logical`, the function will now always return a logical value
* Renamed parameter `filter_specimen` to `specimen_group`, although using `filter_specimen` will still work
* A note to the manual pages of the `portion` functions, that low counts can influence the outcome and that the `portion` functions may camouflage this, since they only return the portion (albeit being dependent on the `minimum` parameter)
* Will now use a column named like "patid" for the patient ID (argument `col_patientid`), when this argument was left blank
* Will now use a column named like "key(...)ab" or "key(...)antibiotics" for the key antibiotics (argument `col_keyantibiotics()`), when this argument was left blank
* Removed argument `output_logical`, the function will now always return a logical value
* Renamed argument `filter_specimen` to `specimen_group`, although using `filter_specimen` will still work
* A note to the manual pages of the `portion` functions, that low counts can influence the outcome and that the `portion` functions may camouflage this, since they only return the portion (albeit being dependent on the `minimum` argument)
* Merged data sets `microorganisms.certe` and `microorganisms.umcg` into `microorganisms.codes`
* Function `mo_taxonomy()` now contains the kingdom too
* Reduce false positives for `is.rsi.eligible()` using the new `threshold` parameter
* Reduce false positives for `is.rsi.eligible()` using the new `threshold` argument
* New colours for `scale_rsi_colours()`
* Summaries of class `mo` will now return the top 3 and the unique count, e.g. using `summary(mo)`
* Small text updates to summaries of class `rsi` and `mic`
@@ -672,16 +862,16 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
freq(mo_genus(mo))
```
* Header info is now available as a list, with the `header` function
* The parameter `header` is now set to `TRUE` at default, even for markdown
* The argument `header` is now set to `TRUE` at default, even for markdown
* Added header info for class `mo` to show unique count of families, genera and species
* Now honours the `decimal.mark` setting, which just like `format` defaults to `getOption("OutDec")`
* The new `big.mark` parameter will at default be `","` when `decimal.mark = "."` and `"."` otherwise
* The new `big.mark` argument will at default be `","` when `decimal.mark = "."` and `"."` otherwise
* Fix for header text where all observations are `NA`
* New parameter `droplevels` to exclude empty factor levels when input is a factor
* New argument `droplevels` to exclude empty factor levels when input is a factor
* Factor levels will be in header when present in input data (maximum of 5)
* Fix for using `select()` on frequency tables
* Function `scale_y_percent()` now contains the `limits` parameter
* Automatic parameter filling for `mdro()`, `key_antibiotics()` and `eucast_rules()`
* Function `scale_y_percent()` now contains the `limits` argument
* Automatic argument filling for `mdro()`, `key_antibiotics()` and `eucast_rules()`
* Updated examples for resistance prediction (`resistance_predict()` function)
* Fix for `as.mic()` to support more values ending in (several) zeroes
* if using different lengths of pattern and x in `%like%`, it will now return the call
@@ -694,7 +884,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
#### New
* Repository moved to GitLab
* Function `count_all` to get all available isolates (that like all `portion_*` and `count_*` functions also supports `summarise` and `group_by`), the old `n_rsi` is now an alias of `count_all`
* Function `get_locale` to determine language for language-dependent output for some `mo_*` functions. This is now the default value for their `language` parameter, by which the system language will be used at default.
* Function `get_locale` to determine language for language-dependent output for some `mo_*` functions. This is now the default value for their `language` argument, by which the system language will be used at default.
* Data sets `microorganismsDT`, `microorganisms.prevDT`, `microorganisms.unprevDT` and `microorganisms.oldDT` to improve the speed of `as.mo`. They are for reference only, since they are primarily for internal use of `as.mo`.
* Function `read.4D` to read from the 4D database of the MMB department of the UMCG
* Functions `mo_authors` and `mo_year` to get specific values about the scientific reference of a taxonomic entry
@@ -703,13 +893,13 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Functions `MDRO`, `BRMO`, `MRGN` and `EUCAST_exceptional_phenotypes` were renamed to `mdro`, `brmo`, `mrgn` and `eucast_exceptional_phenotypes`
* `EUCAST_rules` was renamed to `eucast_rules`, the old function still exists as a deprecated function
* Big changes to the `eucast_rules` function:
* Now also applies rules from the EUCAST 'Breakpoint tables for bacteria', version 8.1, 2018, http://www.eucast.org/clinical_breakpoints/ (see Source of the function)
* New parameter `rules` to specify which rules should be applied (expert rules, breakpoints, others or all)
* New parameter `verbose` which can be set to `TRUE` to get very specific messages about which columns and rows were affected
* Now also applies rules from the EUCAST 'Breakpoint tables for bacteria', version 8.1, 2018, https://www.eucast.org/clinical_breakpoints/ (see Source of the function)
* New argument `rules` to specify which rules should be applied (expert rules, breakpoints, others or all)
* New argument `verbose` which can be set to `TRUE` to get very specific messages about which columns and rows were affected
* Better error handling when rules cannot be applied (i.e. new values could not be inserted)
* The number of affected values will now only be measured once per row/column combination
* Data set `septic_patients` now reflects these changes
* Added parameter `pipe` for piperacillin (J01CA12), also to the `mdro` function
* Added argument `pipe` for piperacillin (J01CA12), also to the `mdro` function
* Small fixes to EUCAST clinical breakpoint rules
* Added column `kingdom` to the microorganisms data set, and function `mo_kingdom` to look up values
* Tremendous speed improvement for `as.mo` (and subsequently all `mo_*` functions), as empty values wil be ignored *a priori*
@@ -721,10 +911,10 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
as.mo("S. spp") # B_STPHY
mo_fullname("S. species") # "Staphylococcus species"
```
* Added parameter `combine_IR` (TRUE/FALSE) to functions `portion_df` and `count_df`, to indicate that all values of I and R must be merged into one, so the output only consists of S vs. IR (susceptible vs. non-susceptible)
* Added argument `combine_IR` (TRUE/FALSE) to functions `portion_df` and `count_df`, to indicate that all values of I and R must be merged into one, so the output only consists of S vs. IR (susceptible vs. non-susceptible)
* Fix for `portion_*(..., as_percent = TRUE)` when minimal number of isolates would not be met
* Added parameter `also_single_tested` for `portion_*` and `count_*` functions to also include cases where not all antibiotics were tested but at least one of the tested antibiotics includes the target antimicribial interpretation, see `?portion`
* Using `portion_*` functions now throws a warning when total available isolate is below parameter `minimum`
* Added argument `also_single_tested` for `portion_*` and `count_*` functions to also include cases where not all antibiotics were tested but at least one of the tested antibiotics includes the target antimicribial interpretation, see `?portion`
* Using `portion_*` functions now throws a warning when total available isolate is below argument `minimum`
* Functions `as.mo`, `as.rsi`, `as.mic`, `as.atc` and `freq` will not set package name as attribute anymore
* Frequency tables - `freq()`:
* Support for grouping variables, test with:
@@ -743,17 +933,17 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Now prints in markdown at default in non-interactive sessions
* No longer adds the factor level column and sorts factors on count again
* Support for class `difftime`
* New parameter `na`, to choose which character to print for empty values
* New parameter `header` to turn the header info off (default when `markdown = TRUE`)
* New parameter `title` to manually setbthe title of the frequency table
* `first_isolate` now tries to find columns to use as input when parameters are left blank
* New argument `na`, to choose which character to print for empty values
* New argument `header` to turn the header info off (default when `markdown = TRUE`)
* New argument `title` to manually setbthe title of the frequency table
* `first_isolate` now tries to find columns to use as input when arguments are left blank
* Improvements for MDRO algorithm (function `mdro`)
* Data set `septic_patients` is now a `data.frame`, not a tibble anymore
* Removed diacritics from all authors (columns `microorganisms$ref` and `microorganisms.old$ref`) to comply with CRAN policy to only allow ASCII characters
* Fix for `mo_property` not working properly
* Fix for `eucast_rules` where some Streptococci would become ceftazidime R in EUCAST rule 4.5
* Support for named vectors of class `mo`, useful for `top_freq()`
* `ggplot_rsi` and `scale_y_percent` have `breaks` parameter
* `ggplot_rsi` and `scale_y_percent` have `breaks` argument
* AI improvements for `as.mo`:
* `"CRS"` -> *Stenotrophomonas maltophilia*
* `"CRSM"` -> *Stenotrophomonas maltophilia*
@@ -820,7 +1010,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
# min median max neval
# 0.01817717 0.01843957 0.03878077 100
```
* Added parameter `reference_df` for `as.mo`, so users can supply their own microbial IDs, name or codes as a reference table
* Added argument `reference_df` for `as.mo`, so users can supply their own microbial IDs, name or codes as a reference table
* Renamed all previous references to `bactid` to `mo`, like:
* Column names inputs of `EUCAST_rules`, `first_isolate` and `key_antibiotics`
* Column names of datasets `microorganisms` and `septic_patients`
@@ -849,7 +1039,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Fix for `as.mic` for values ending in zeroes after a real number
* Small fix where *B. fragilis* would not be found in the `microorganisms.umcg` data set
* Added `prevalence` column to the `microorganisms` data set
* Added parameters `minimum` and `as_percent` to `portion_df`
* Added arguments `minimum` and `as_percent` to `portion_df`
* Support for quasiquotation in the functions series `count_*` and `portions_*`, and `n_rsi`. This allows to check for more than 2 vectors or columns.
```r
septic_patients %>% select(amox, cipr) %>% count_IR()
@@ -860,12 +1050,12 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
septic_patients %>% portion_S(amcl, gent)
septic_patients %>% portion_S(amcl, gent, pita)
```
* Edited `ggplot_rsi` and `geom_rsi` so they can cope with `count_df`. The new `fun` parameter has value `portion_df` at default, but can be set to `count_df`.
* Edited `ggplot_rsi` and `geom_rsi` so they can cope with `count_df`. The new `fun` argument has value `portion_df` at default, but can be set to `count_df`.
* Fix for `ggplot_rsi` when the `ggplot2` package was not loaded
* Added datalabels function `labels_rsi_count` to `ggplot_rsi`
* Added possibility to set any parameter to `geom_rsi` (and `ggplot_rsi`) so you can set your own preferences
* Added possibility to set any argument to `geom_rsi` (and `ggplot_rsi`) so you can set your own preferences
* Fix for joins, where predefined suffices would not be honoured
* Added parameter `quote` to the `freq` function
* Added argument `quote` to the `freq` function
* Added generic function `diff` for frequency tables
* Added longest en shortest character length in the frequency table (`freq`) header of class `character`
* Support for types (classes) list and matrix for `freq`
@@ -922,7 +1112,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
#### Changed
* Improvements for forecasting with `resistance_predict` and added more examples
* More antibiotics added as parameters for EUCAST rules
* More antibiotics added as arguments for EUCAST rules
* Updated version of the `septic_patients` data set to better reflect the reality
* Pretty printing for tibbles removed as it is not really the scope of this package
* Printing of `mic` and `rsi` classes now returns all values - use `freq` to check distributions
@@ -930,7 +1120,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Column names for the `key_antibiotics` function are now generic: 6 for broadspectrum ABs, 6 for Gram-positive specific and 6 for Gram-negative specific ABs
* Speed improvement for the `abname` function
* `%like%` now supports multiple patterns
* Frequency tables are now actual `data.frame`s with altered console printing to make it look like a frequency table. Because of this, the parameter `toConsole` is not longer needed.
* Frequency tables are now actual `data.frame`s with altered console printing to make it look like a frequency table. Because of this, the argument `toConsole` is not longer needed.
* Fix for `freq` where the class of an item would be lost
* Small translational improvements to the `septic_patients` dataset and the column `bactid` now has the new class `"bactid"`
* Small improvements to the `microorganisms` dataset (especially for *Salmonella*) and the column `bactid` now has the new class `"bactid"`
@@ -963,7 +1153,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Function `guess_atc` to **determine the ATC** of an antibiotic based on name, trade name, or known abbreviations
* Function `freq` to create **frequency tables**, with additional info in a header
* Function `MDRO` to **determine Multi Drug Resistant Organisms (MDRO)** with support for country-specific guidelines.
* [Exceptional resistances defined by EUCAST](http://www.eucast.org/expert_rules_and_intrinsic_resistance) are also supported instead of countries alone
* [Exceptional resistances defined by EUCAST](https://www.eucast.org/expert_rules_and_intrinsic_resistance/) are also supported instead of countries alone
* Functions `BRMO` and `MRGN` are wrappers for Dutch and German guidelines, respectively
* New algorithm to determine weighted isolates, can now be `"points"` or `"keyantibiotics"`, see `?first_isolate`
* New print format for `tibble`s and `data.table`s
@@ -978,7 +1168,7 @@ We've got a new website: [https://msberends.gitlab.io/AMR](https://msberends.git
* Added support for character vector in `join` functions
* Added warnings when a join results in more rows after than before the join
* Altered `%like%` to make it case insensitive
* For parameters of functions `first_isolate` and `EUCAST_rules` column names are now case-insensitive
* For arguments of functions `first_isolate` and `EUCAST_rules` column names are now case-insensitive
* Functions `as.rsi` and `as.mic` now add the package name and version as attributes
#### Other

View File

@@ -1,64 +1,67 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# functions from dplyr, will perhaps become poorman
distinct <- function(.data, ..., .keep_all = FALSE) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
distinct.grouped_data(.data, ..., .keep_all = .keep_all)
} else {
distinct.default(.data, ..., .keep_all = .keep_all)
}
}
distinct.default <- function(.data, ..., .keep_all = FALSE) {
names <- rownames(.data)
rownames(.data) <- NULL
if (length(deparse_dots(...)) == 0) {
selected <- .data
} else {
selected <- select(.data, ...)
}
rows <- as.integer(rownames(unique(selected)))
if (isTRUE(.keep_all)) {
res <- .data[rows, , drop = FALSE]
} else {
res <- selected[rows, , drop = FALSE]
}
rownames(res) <- names[rows]
res
}
distinct.grouped_data <- function(.data, ..., .keep_all = FALSE) {
apply_grouped_function(.data, "distinct", ..., .keep_all = .keep_all)
}
filter_join_worker <- function(x, y, by = NULL, type = c("anti", "semi")) {
type <- match.arg(type, choices = c("anti", "semi"), several.ok = FALSE)
# faster implementation of left_join than using merge() by poorman - we use match():
pm_left_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
if (is.null(by)) {
by <- intersect(names(x), names(y))
join_message(by)
by <- intersect(names(x), names(y))[1L]
if (is.na(by)) {
stop_("no common column found for pm_left_join()")
}
pm_join_message(by)
} else if (!is.null(names(by))) {
by <- unname(c(names(by), by))
}
rows <- interaction(x[, by]) %in% interaction(y[, by])
if (type == "anti") rows <- !rows
res <- x[rows, , drop = FALSE]
rownames(res) <- NULL
res
if (length(by) == 1) {
by <- rep(by, 2)
}
int_x <- colnames(x) %in% colnames(y) & colnames(x) != by[1]
int_y <- colnames(y) %in% colnames(x) & colnames(y) != by[2]
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]),
colnames(y)[!colnames(y) %in% colnames(x) & !colnames(y) == by[2]],
drop = FALSE])
rownames(merged) <- NULL
merged
}
quick_case_when <- function(...) {
vectors <- list(...)
split <- lapply(vectors, function(x) unlist(strsplit(paste(deparse(x), collapse = ""), "~", fixed = TRUE)))
for (i in seq_len(length(vectors))) {
if (eval(parse(text = split[[i]][1]), envir = parent.frame())) {
return(eval(parse(text = split[[i]][2]), envir = parent.frame()))
}
}
return(NA)
}
# No export, no Rd
@@ -76,39 +79,51 @@ check_dataset_integrity <- function() {
data_in_pkg <- data(package = "AMR", envir = asNamespace("AMR"))$results[, "Item", drop = TRUE]
data_in_globalenv <- ls(envir = globalenv())
overwritten <- data_in_pkg[data_in_pkg %in% data_in_globalenv]
stop_if(length(overwritten) > 0,
"the following data set is overwritten by your global environment and prevents the AMR package from working correctly:\n",
paste0("'", overwritten, "'", collapse = ", "),
".\nPlease rename your object before using this function.", call = FALSE)
# exception for example_isolates
overwritten <- overwritten[overwritten != "example_isolates"]
if (length(overwritten) > 0) {
warning_(ifelse(length(overwritten) == 1,
"The following data set is overwritten by your global environment and prevents the AMR package from working correctly: ",
"The following data sets are overwritten by your global environment and prevent the AMR package from working correctly: "),
paste0("'", overwritten, "'", collapse = ", "),
".\nPlease rename your object(s).", call = FALSE)
}
# check if other packages did not overwrite our data sets
tryCatch({
check_microorganisms <- all(c("mo", "fullname", "kingdom", "phylum",
"class", "order", "family", "genus",
"class", "order", "family", "genus",
"species", "subspecies", "rank",
"species_id", "source", "ref", "prevalence") %in% colnames(microorganisms),
na.rm = TRUE)
check_antibiotics <- all(c("ab", "atc", "cid", "name", "group",
check_antibiotics <- all(c("ab", "atc", "cid", "name", "group",
"atc_group1", "atc_group2", "abbreviations",
"synonyms", "oral_ddd", "oral_units",
"synonyms", "oral_ddd", "oral_units",
"iv_ddd", "iv_units", "loinc") %in% colnames(antibiotics),
na.rm = TRUE)
}, error = function(e)
stop_('please use the command \'library("AMR")\' before using this function, to load the required reference data.', call = FALSE)
)
}, error = function(e) {
# package not yet loaded
require("AMR")
})
stop_if(!check_microorganisms | !check_antibiotics,
"the data set `microorganisms` or `antibiotics` was overwritten in your environment because another package with the same object names was loaded _after_ the AMR package, preventing the AMR package from working correctly. Please load the AMR package last.")
invisible(TRUE)
}
search_type_in_df <- function(x, type) {
search_type_in_df <- function(x, type, info = TRUE) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(type, allow_class = "character", has_length = 1)
# try to find columns based on type
found <- NULL
# remove attributes from other packages
x <- as.data.frame(x, stringsAsFactors = FALSE)
colnames(x) <- trimws(colnames(x))
# -- mo
if (type == "mo") {
if (any(sapply(x, is.mo))) {
found <- sort(colnames(x)[sapply(x, is.mo)])[1]
if (any(vapply(FUN.VALUE = logical(1), x, is.mo))) {
found <- sort(colnames(x)[vapply(FUN.VALUE = logical(1), x, is.mo)])[1]
} else if ("mo" %in% colnames(x) &
suppressWarnings(
all(x$mo %in% c(NA,
@@ -122,7 +137,7 @@ search_type_in_df <- function(x, type) {
} else if (any(colnames(x) %like% "species")) {
found <- sort(colnames(x)[colnames(x) %like% "species"])[1]
}
}
# -- key antibiotics
if (type == "keyantibiotics") {
@@ -135,13 +150,13 @@ search_type_in_df <- function(x, type) {
if (any(colnames(x) %like% "^(specimen date|specimen_date|spec_date)")) {
# WHONET support
found <- sort(colnames(x)[colnames(x) %like% "^(specimen date|specimen_date|spec_date)"])[1]
if (!any(class(pull(x, found)) %in% c("Date", "POSIXct"))) {
stop(font_red(paste0("ERROR: Found column `", font_bold(found), "` to be used as input for `col_", type,
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)
}
} else if (any(sapply(x, function(x) inherits(x, c("Date", "POSIXct"))))) {
found <- sort(colnames(x)[sapply(x, function(x) inherits(x, c("Date", "POSIXct")))])[1]
} else if (any(vapply(FUN.VALUE = logical(1), x, function(x) inherits(x, c("Date", "POSIXct"))))) {
found <- sort(colnames(x)[vapply(FUN.VALUE = logical(1), x, function(x) inherits(x, c("Date", "POSIXct")))])[1]
}
}
# -- patient id
@@ -168,33 +183,43 @@ search_type_in_df <- function(x, type) {
if (!is.null(found)) {
# this column should contain logicals
if (!is.logical(x[, found, drop = TRUE])) {
message(font_red(paste0("NOTE: Column `", font_bold(found), "` found as input for `col_", type,
"`, but this column does not contain 'logical' values (TRUE/FALSE) and was ignored.")))
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)
found <- NULL
}
}
}
if (!is.null(found)) {
msg <- paste0("NOTE: Using column `", font_bold(found), "` as input for `col_", type, "`.")
if (type %in% c("keyantibiotics", "specimen")) {
msg <- paste(msg, "Use", font_bold(paste0("col_", type), "= FALSE"), "to prevent this.")
if (!is.null(found) & info == TRUE) {
if (message_not_thrown_before(fn = paste0("search_", type))) {
msg <- paste0("Using column '", font_bold(found), "' as input for `col_", type, "`.")
if (type %in% c("keyantibiotics", "specimen")) {
msg <- paste(msg, "Use", font_bold(paste0("col_", type), "= FALSE"), "to prevent this.")
}
message_(msg)
remember_thrown_message(fn = paste0("search_", type))
}
message(font_blue(msg))
}
found
}
is_possibly_regex <- function(x) {
tryCatch(vapply(FUN.VALUE = character(1), strsplit(x, ""),
function(y) any(y %in% c("$", "(", ")", "*", "+", "-", ".", "?", "[", "]", "^", "{", "|", "}", "\\"), na.rm = TRUE)),
error = function(e) rep(TRUE, length(x)))
}
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
sapply(package, function(pkg)
vapply(FUN.VALUE = character(1), package, function(pkg)
tryCatch(get(".packageName", envir = asNamespace(pkg)),
error = function(e) {
if (package == "rstudioapi") {
stop("This function only works in RStudio.", call. = FALSE)
} else if (pkg != "base") {
stop("package '", pkg, "' required but not installed.",
stop("This requires the '", pkg, "' package.",
"\nTry to install it with: install.packages(\"", pkg, "\")",
call. = FALSE)
}
@@ -202,13 +227,121 @@ stop_ifnot_installed <- function(package) {
return(invisible())
}
import_fn <- function(name, pkg) {
stop_ifnot_installed(pkg)
import_fn <- function(name, pkg, error_on_fail = TRUE) {
if (isTRUE(error_on_fail)) {
stop_ifnot_installed(pkg)
}
tryCatch(
get(name, envir = asNamespace(pkg)),
error = function(e) stop_("an error occurred in import_fn() while using this function", call = FALSE))
# don't use get() to avoid fetching non-API functions
getExportedValue(name = name, ns = asNamespace(pkg)),
error = function(e) {
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)
} else {
return(NULL)
}
})
}
# this alternative wrapper to the message(), warning() and stop() functions:
# - wraps text to never break lines within words
# - ignores formatted text while wrapping
# - adds indentation dependent on the type of message (such as NOTE)
# - can add additional formatting functions like blue or bold text
word_wrap <- function(...,
add_fn = list(),
as_note = FALSE,
width = 0.95 * getOption("width"),
extra_indent = 0) {
msg <- paste0(c(...), collapse = "")
if (isTRUE(as_note)) {
msg <- paste0("NOTE: ", gsub("^note:? ?", "", msg, ignore.case = TRUE))
}
if (msg %like% "\n") {
# run word_wraps() over every line here, bind them and return again
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"))
}
# we need to correct for already applied style, that adds text like "\033[31m\"
msg_stripped <- font_stripstyle(msg)
# where are the spaces now?
msg_stripped_wrapped <- paste0(strwrap(msg_stripped,
simplify = TRUE,
width = width),
collapse = "\n")
msg_stripped_wrapped <- paste0(unlist(strsplit(msg_stripped_wrapped, "(\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
replace_spaces <- which(!msg_stripped_spaces %in% msg_stripped_wrapped_spaces)
# put it together
msg <- unlist(strsplit(msg, " "))
msg[replace_spaces] <- paste0(msg[replace_spaces], "\n")
msg <- paste0(msg, collapse = " ")
msg <- gsub("\n ", "\n", msg, fixed = TRUE)
if (msg_stripped %like% "^NOTE: ") {
indentation <- 6 + extra_indent
} else if (msg_stripped %like% "^=> ") {
indentation <- 3 + extra_indent
} else {
indentation <- 0 + extra_indent
}
msg <- gsub("\n", paste0("\n", strrep(" ", indentation)), msg, fixed = TRUE)
# remove trailing empty characters
msg <- gsub("(\n| )+$", "", msg)
if (length(add_fn) > 0) {
if (!is.list(add_fn)) {
add_fn <- list(add_fn)
}
for (i in seq_len(length(add_fn))) {
msg <- add_fn[[i]](msg)
}
}
# format backticks
msg <- gsub("(`.+?`)", font_grey_bg("\\1"), msg)
msg
}
message_ <- function(...,
appendLF = TRUE,
add_fn = list(font_blue),
as_note = TRUE) {
message(word_wrap(...,
add_fn = add_fn,
as_note = as_note),
appendLF = appendLF)
}
warning_ <- function(...,
add_fn = list(),
immediate = FALSE,
call = TRUE) {
warning(word_wrap(...,
add_fn = add_fn,
as_note = FALSE),
immediate. = immediate,
call. = call)
}
# this alternative to the stop() function:
# - adds the function name where the error was thrown
# - wraps text to never break lines within words
stop_ <- function(..., call = TRUE) {
msg <- paste0(c(...), collapse = "")
if (!isFALSE(call)) {
@@ -220,6 +353,7 @@ stop_ <- function(..., call = TRUE) {
}
msg <- paste0("in ", call, "(): ", msg)
}
msg <- word_wrap(msg, add_fn = list(), as_note = FALSE)
stop(msg, call. = FALSE)
}
@@ -237,7 +371,7 @@ stop_if <- function(expr, ..., call = TRUE) {
}
stop_ifnot <- function(expr, ..., call = TRUE) {
if (!isTRUE(expr)) {
if (isFALSE(expr)) {
if (isTRUE(call)) {
call <- -1
}
@@ -264,7 +398,7 @@ stop_ifnot <- function(expr, ..., call = TRUE) {
class_integrity_check <- function(value, type, check_vector) {
if (!all(value[!is.na(value)] %in% check_vector)) {
warning(paste0("invalid ", type, ", NA generated"), call. = FALSE)
warning_(paste0("invalid ", type, ", NA generated"), call = FALSE)
value[!value %in% check_vector] <- NA
}
value
@@ -295,8 +429,248 @@ dataset_UTF8_to_ASCII <- function(df) {
df
}
# for eucast_rules() and mdro(), creates markdown output with URLs and names
create_ab_documentation <- function(ab) {
ab_names <- ab_name(ab, language = NULL, tolower = TRUE)
ab <- ab[order(ab_names)]
ab_names <- ab_names[order(ab_names)]
atcs <- ab_atc(ab)
atcs[!is.na(atcs)] <- paste0("[", atcs[!is.na(atcs)], "](", ab_url(ab[!is.na(atcs)]), ")")
atcs[is.na(atcs)] <- "no ATC code"
out <- paste0(ab_names, " (`", ab, "`, ", atcs, ")", collapse = ", ")
substr(out, 1, 1) <- toupper(substr(out, 1, 1))
out
}
vector_or <- function(v, quotes = TRUE, reverse = FALSE) {
# makes unique and sorts, and this also removed NAs
v <- sort(unique(v))
if (length(v) == 1) {
return(paste0(ifelse(quotes, '"', ""), v, ifelse(quotes, '"', "")))
}
if (reverse == TRUE) {
v <- rev(v)
}
# all commas except for last item, so will become '"val1", "val2", "val3" or "val4"'
paste0(paste0(ifelse(quotes, '"', ""), v[seq_len(length(v) - 1)], ifelse(quotes, '"', ""), collapse = ", "),
" or ", paste0(ifelse(quotes, '"', ""), v[length(v)], ifelse(quotes, '"', "")))
}
format_class <- function(class, plural) {
class.bak <- class
class[class %in% c("numeric", "double")] <- "number"
class[class == "integer"] <- "whole number"
if (any(c("numeric", "double") %in% class.bak, na.rm = TRUE) & "integer" %in% class.bak) {
class[class %in% c("number", "whole number")] <- "(whole) number"
}
class[class == "character"] <- "text string"
class[class %in% c("Date", "POSIXt")] <- "date"
class[class != class.bak] <- paste0(ifelse(plural, "", "a "),
class[class != class.bak],
ifelse(plural, "s", ""))
# exceptions
class[class == "logical"] <- ifelse(plural, "a vector of `TRUE`/`FALSE`", "`TRUE` or `FALSE`")
if ("data.frame" %in% class) {
class <- "a data set"
}
if ("list" %in% class) {
class <- "a list"
}
if ("matrix" %in% class) {
class <- "a matrix"
}
if ("isolate_identifier" %in% class) {
class <- "created with isolate_identifier()"
}
if (any(c("mo", "ab", "rsi", "disk", "mic") %in% class)) {
class <- paste0("of class <", class[1L], ">")
}
class[class == class.bak] <- paste0("of class <", class[class == class.bak], ">")
# output
vector_or(class, quotes = FALSE)
}
# a check for every single argument in all functions
meet_criteria <- function(object,
allow_class = NULL,
has_length = NULL,
looks_like = NULL,
is_in = NULL,
contains_column_class = NULL,
allow_NULL = FALSE,
allow_NA = FALSE,
ignore.case = FALSE,
.call_depth = 0) { # depth in calling
obj_name <- deparse(substitute(object))
call_depth <- -2 - abs(.call_depth)
if (is.null(object)) {
stop_if(allow_NULL == FALSE, "argument `", obj_name, "` must not be NULL", call = call_depth)
return(invisible())
}
if (is.null(dim(object)) && length(object) == 1 && suppressWarnings(is.na(object))) { # suppressWarnings for functions
stop_if(allow_NA == FALSE, "argument `", obj_name, "` must not be NA", call = call_depth)
return(invisible())
}
if (!is.null(allow_class)) {
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)
# 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)
}
}
if (!is.null(has_length)) {
stop_ifnot(length(object) %in% has_length, "argument `", obj_name,
"` must ", # ifelse(allow_NULL, "be NULL or must ", ""),
"be of length ", vector_or(has_length, quotes = FALSE),
", not ", length(object),
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)
}
if (!is.null(is_in)) {
if (ignore.case == TRUE) {
object <- tolower(object)
is_in <- tolower(is_in)
}
stop_ifnot(all(object %in% is_in, na.rm = TRUE), "argument `", obj_name,
"` must be ",
ifelse(!is.null(has_length) && length(has_length) == 1 && has_length == 1, "either ", ""),
vector_or(is_in, quotes = !isTRUE(any(c("double", "numeric", "integer") %in% allow_class))),
call = call_depth)
}
if (!is.null(contains_column_class)) {
stop_ifnot(any(vapply(FUN.VALUE = logical(1),
object,
function(col, columns_class = contains_column_class) {
inherits(col, columns_class)
}), 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)
}
return(invisible())
}
get_current_data <- function(arg_name, call) {
# try dplyr::cur_data_all() first to support dplyr groups
# only useful for e.g. dplyr::filter(), dplyr::mutate() and dplyr::summarise()
# not useful (throws error) with e.g. dplyr::select() - but that will be caught later in this function
cur_data_all <- import_fn("cur_data_all", "dplyr", error_on_fail = FALSE)
if (!is.null(cur_data_all)) {
out <- tryCatch(cur_data_all(), error = function(e) NULL)
if (is.data.frame(out)) {
return(out)
}
}
if (as.double(R.Version()$major) + (as.double(R.Version()$minor) / 10) < 3.2) {
# R-3.0 and R-3.1 do not have an `x` element in the call stack, rendering this function useless
if (is.na(arg_name)) {
# like in carbapenems() etc.
warning_("this function can only be used in R >= 3.2", call = call)
return(data.frame())
} else {
stop_("argument `", arg_name, "` is missing with no default", call = call)
}
}
# try a (base R) method, by going over the complete system call stack with sys.frames()
not_set <- TRUE
frms <- lapply(sys.frames(), function(el) {
if (not_set == TRUE && ".Generic" %in% names(el)) {
if (tryCatch(".data" %in% names(el) && is.data.frame(el$`.data`), error = function(e) FALSE)) {
# dplyr? - an element `.data` will be in the system call stack
# will be used in dplyr::select() (but not in dplyr::filter(), dplyr::mutate() or dplyr::summarise())
not_set <<- FALSE
el$`.data`
} else if (tryCatch(any(c("x", "xx") %in% names(el)), error = function(e) FALSE)) {
# otherwise try base R:
# an element `x` will be in this environment for only cols, e.g. `example_isolates[, carbapenems()]`
# an element `xx` will be in this environment for rows + cols, e.g. `example_isolates[c(1:3), carbapenems()]`
if (tryCatch(is.data.frame(el$xx), error = function(e) FALSE)) {
not_set <<- FALSE
el$xx
} else if (tryCatch(is.data.frame(el$x))) {
not_set <<- FALSE
el$x
} else {
NULL
}
} else {
NULL
}
} else {
NULL
}
})
vars_df <- tryCatch(frms[[which(!vapply(FUN.VALUE = logical(1), frms, is.null))]], error = function(e) NULL)
if (is.data.frame(vars_df)) {
return(vars_df)
}
# nothing worked, so:
if (is.na(arg_name)) {
stop_("this function must be used inside valid dplyr selection verbs or inside a data.frame call",
call = call)
} else {
stop_("argument `", arg_name, "` is missing with no default", call = call)
}
}
unique_call_id <- function(entire_session = FALSE) {
if (entire_session == TRUE) {
c(envir = "session",
call = "session")
} else {
# combination of environment ID (like "0x7fed4ee8c848")
# and highest system call
c(envir = gsub("<environment: (.*)>", "\\1", utils::capture.output(sys.frames()[[1]])),
call = paste0(deparse(sys.calls()[[1]]), collapse = ""))
}
}
remember_thrown_message <- function(fn, entire_session = FALSE) {
# this is to prevent that messages/notes will be printed for every dplyr group
# e.g. this would show a msg 4 times: example_isolates %>% group_by(hospital_id) %>% filter(mo_is_gram_negative())
assign(x = paste0("thrown_msg.", fn),
value = unique_call_id(entire_session = entire_session),
envir = pkg_env)
}
message_not_thrown_before <- function(fn, entire_session = FALSE) {
is.null(pkg_env[[paste0("thrown_msg.", fn)]]) || !identical(pkg_env[[paste0("thrown_msg.", fn)]], unique_call_id(entire_session))
}
reset_all_thrown_messages <- function() {
# for unit tests, where the environment and highest system call do not change
pkg_env_contents <- ls(envir = pkg_env)
rm(list = pkg_env_contents[pkg_env_contents %like% "^thrown_msg."],
envir = pkg_env)
}
has_colour <- function() {
# this is a base R version of crayon::has_color
# this is a base R version of crayon::has_color, but disables colours on emacs
if (Sys.getenv("EMACS") != "" || Sys.getenv("INSIDE_EMACS") != "") {
# disable on emacs, which only supports 8 colours
return(FALSE)
}
enabled <- getOption("crayon.enabled")
if (!is.null(enabled)) {
return(isTRUE(enabled))
@@ -326,33 +700,19 @@ has_colour <- function() {
}
return(FALSE)
}
emacs_version <- function() {
ver <- Sys.getenv("INSIDE_EMACS")
if (ver == "") {
return(NA_integer_)
}
ver <- gsub("'", "", ver)
ver <- strsplit(ver, ",", fixed = TRUE)[[1]]
ver <- strsplit(ver, ".", fixed = TRUE)[[1]]
as.numeric(ver)
}
if ((Sys.getenv("EMACS") != "" || Sys.getenv("INSIDE_EMACS") != "") &&
!is.na(emacs_version()[1]) && emacs_version()[1] >= 23) {
return(TRUE)
}
if ("COLORTERM" %in% names(Sys.getenv())) {
return(TRUE)
}
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)
}
# the crayon colours
# set colours if console has_colour()
try_colour <- function(..., before, after, collapse = " ") {
txt <- paste0(unlist(list(...)), collapse = collapse)
if (isTRUE(has_colour())) {
@@ -395,15 +755,30 @@ font_subtle <- function(..., collapse = " ") {
font_grey <- function(..., collapse = " ") {
try_colour(..., before = "\033[38;5;249m", after = "\033[39m", collapse = collapse)
}
font_grey_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[48;5;254m", after = "\033[49m", collapse = collapse)
}
font_green_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[42m", after = "\033[49m", collapse = collapse)
}
font_rsi_R_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[48;5;202m", after = "\033[49m", collapse = collapse)
}
font_rsi_S_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[48;5;76m", after = "\033[49m", collapse = collapse)
}
font_rsi_I_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[48;5;148m", after = "\033[49m", collapse = collapse)
}
font_red_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[41m", after = "\033[49m", collapse = collapse)
}
font_yellow_bg <- function(..., collapse = " ") {
try_colour(..., before = "\033[43m", after = "\033[49m", collapse = collapse)
}
font_na <- function(..., collapse = " ") {
font_red(..., collapse = collapse)
}
font_bold <- function(..., collapse = " ") {
try_colour(..., before = "\033[1m", after = "\033[22m", collapse = collapse)
}
@@ -418,7 +793,7 @@ font_stripstyle <- function(x) {
gsub("(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]", "", x, perl = TRUE)
}
progress_estimated <- function(n = 1, n_min = 0, ...) {
progress_ticker <- function(n = 1, n_min = 0, ...) {
if (!interactive() || n < n_min) {
pb <- list()
pb$tick <- function() {
@@ -427,7 +802,7 @@ progress_estimated <- function(n = 1, n_min = 0, ...) {
pb$kill <- function() {
invisible()
}
structure(pb, class = "txtProgressBar")
set_clean_class(pb, new_class = "txtProgressBar")
} else if (n >= n_min) {
pb <- utils::txtProgressBar(max = n, style = 3)
pb$tick <- function() {
@@ -437,6 +812,90 @@ progress_estimated <- function(n = 1, n_min = 0, ...) {
}
}
set_clean_class <- function(x, new_class) {
# return the object with only the new class and no additional attributes where possible
if (is.null(x)) {
x <- NA_character_
}
if (is.factor(x)) {
# keep only levels and remove all other attributes
lvls <- levels(x)
attributes(x) <- NULL
levels(x) <- lvls
} else if (!is.list(x) && !is.function(x)) {
attributes(x) <- NULL
}
class(x) <- new_class
x
}
formatted_filesize <- function(...) {
size_kb <- file.size(...) / 1024
if (size_kb < 1) {
paste(round(size_kb, 1), "kB")
} else if (size_kb < 100) {
paste(round(size_kb, 0), "kB")
} else {
paste(round(size_kb / 1024, 1), "MB")
}
}
create_pillar_column <- function(x, ...) {
new_pillar_shaft_simple <- import_fn("new_pillar_shaft_simple", "pillar", error_on_fail = FALSE)
if (!is.null(new_pillar_shaft_simple)) {
new_pillar_shaft_simple(x, ...)
} else {
# does not exist in package 'pillar' anymore
structure(list(x),
class = "pillar_shaft_simple",
...)
}
}
# 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) {
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
pieces <- strsplit(generic, "::")[[1]]
stopifnot(length(pieces) == 2)
package <- pieces[[1]]
generic <- pieces[[2]]
caller <- parent.frame()
get_method_env <- function() {
top <- topenv(caller)
if (isNamespace(top)) {
asNamespace(environmentName(top))
}
else {
caller
}
}
get_method <- function(method, env) {
if (is.null(method)) {
get(paste0(generic, ".", class), envir = get_method_env())
}
else {
method
}
}
method_fn <- get_method(method)
stopifnot(is.function(method_fn))
setHook(packageEvent(package, "onLoad"), function(...) {
ns <- asNamespace(package)
method_fn <- get_method(method)
registerS3method(generic, class, method_fn, envir = ns)
})
if (!isNamespaceLoaded(package)) {
return(invisible())
}
envir <- asNamespace(package)
if (exists(generic, envir)) {
registerS3method(generic, class, method_fn, envir = envir)
}
invisible()
}
# works exactly like round(), but rounds `round2(44.55, 1)` to 44.6 instead of 44.5
# and adds decimal zeroes until `digits` is reached when force_zero = TRUE
round2 <- function(x, digits = 0, force_zero = TRUE) {
@@ -446,12 +905,12 @@ round2 <- function(x, digits = 0, force_zero = TRUE) {
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,
strrep("0",
max(0,
digits - nchar(
format(
as.double(
gsub(".*[.](.*)$",
gsub(".*[.](.*)$",
"\\1",
values_trans)),
scientific = FALSE)))))
@@ -462,7 +921,7 @@ round2 <- function(x, digits = 0, force_zero = TRUE) {
# percentage from our other package: 'cleaner'
percentage <- function(x, digits = NULL, ...) {
# getdecimalplaces() function
getdecimalplaces <- function(x, minimum = 0, maximum = 3) {
if (maximum < minimum) {
@@ -471,20 +930,20 @@ percentage <- function(x, digits = NULL, ...) {
if (minimum > maximum) {
minimum <- maximum
}
max_places <- max(unlist(lapply(strsplit(sub("0+$", "",
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)
}
# format_percentage() function
format_percentage <- function(x, digits = NULL, ...) {
if (is.null(digits)) {
digits <- getdecimalplaces(x)
}
# round right: percentage(0.4455) and format(as.percentage(0.4455), 1) should return "44.6%", not "44.5%"
x_formatted <- format(round2(as.double(x), digits = digits + 2) * 100,
scientific = FALSE,
@@ -495,7 +954,7 @@ percentage <- function(x, digits = NULL, ...) {
x_formatted[!grepl(pattern = "^[0-9.,e-]+$", x = x)] <- NA_character_
x_formatted
}
# the actual working part
x <- as.double(x)
if (is.null(digits)) {
@@ -508,16 +967,16 @@ percentage <- function(x, digits = NULL, ...) {
}
# prevent dependency on package 'backports'
# these functions were not available in previous versions of R (last checked: R 4.0.0)
# these functions were not available in previous versions of R (last checked: R 4.0.3)
# 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)
@@ -525,9 +984,9 @@ strrep <- function(x, times) {
trimws <- function(x, which = c("both", "left", "right")) {
which <- match.arg(which)
mysub <- function(re, x) sub(re, "", x, perl = TRUE)
if (which == "left")
if (which == "left")
return(mysub("^[ \t\r\n]+", x))
if (which == "right")
if (which == "right")
return(mysub("[ \t\r\n]+$", x))
mysub("[ \t\r\n]+$", mysub("^[ \t\r\n]+", x))
}
@@ -537,3 +996,21 @@ isFALSE <- function(x) {
deparse1 <- function(expr, collapse = " ", width.cutoff = 500L, ...) {
paste(deparse(expr, width.cutoff, ...), collapse = collapse)
}
file.size <- function(...) {
file.info(...)$size
}
file.mtime <- function(...) {
file.info(...)$mtime
}
str2lang <- function(s) {
stopifnot(length(s) == 1L)
ex <- parse(text = s, keep.source = FALSE)
stopifnot(length(ex) == 1L)
ex[[1L]]
}
isNamespaceLoaded <- function(pkg) {
pkg %in% loadedNamespaces()
}
lengths <- function(x, use.names = TRUE) {
vapply(x, length, FUN.VALUE = NA_integer_, USE.NAMES = use.names)
}

View File

@@ -1,775 +0,0 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# #
# 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 more info: https://msberends.github.io/AMR. #
# ==================================================================== #
# ------------------------------------------------
# THIS FILE WAS CREATED AUTOMATICALLY!
# Source file: data-raw/reproduction_of_poorman.R
# ------------------------------------------------
# Poorman: a package to replace all dplyr functions with base R so we can lose dependency on dplyr.
# These functions were downloaded from https://github.com/nathaneastwood/poorman,
# from this commit: https://github.com/nathaneastwood/poorman/tree/7d76d77f8f7bc663bf30fb5a161abb49801afa17
#
# All code below was released under MIT license, that permits 'free of charge, to any person obtaining a
# copy of the software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
# is furnished to do so', given that a copyright notice is given in the software.
#
# Copyright notice as found on https://github.com/nathaneastwood/poorman/blob/master/LICENSE on 2 May 2020:
# YEAR: 2020
# COPYRIGHT HOLDER: Nathan Eastwood
arrange <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
arrange.grouped_data(.data, ...)
} else {
arrange.default(.data, ...)
}
}
arrange.default <- function(.data, ...) {
rows <- eval.parent(substitute(with(.data, order(...))))
.data[rows, , drop = FALSE]
}
arrange.grouped_data <- function(.data, ...) {
apply_grouped_function(.data, "arrange", ...)
}
between <- function(x, left, right) {
if (!is.null(attr(x, "class")) && !inherits(x, c("Date", "POSIXct"))) {
warning("`between()` called on numeric vector with S3 class")
}
if (!is.double(x)) x <- as.numeric(x)
x >= as.numeric(left) & x <= as.numeric(right)
}
count <- function(x, ..., wt = NULL, sort = FALSE, name = NULL) {
groups <- get_groups(x)
if (!missing(...)) x <- group_by(x, ..., .add = TRUE)
wt <- deparse_var(wt)
res <- do.call(tally, list(x, wt, sort, name))
if (length(groups) > 0L) res <- do.call(group_by, list(res, as.name(groups)))
res
}
tally <- function(x, wt = NULL, sort = FALSE, name = NULL) {
name <- check_name(x, name)
wt <- deparse_var(wt)
res <- do.call(summarise, set_names(list(x, as.name(tally_n(x, wt))), c(".data", name)))
res <- ungroup(res)
if (isTRUE(sort)) res <- do.call(arrange, list(res, call("desc", as.name(name))))
rownames(res) <- NULL
res
}
add_count <- function(x, ..., wt = NULL, sort = FALSE, name = NULL) {
name <- check_name(x, name)
row_names <- rownames(x)
wt <- deparse_var(wt)
if (!missing(...)) x <- group_by(x, ..., .add = TRUE)
res <- do.call(add_tally, list(x, wt, sort, name))
res[row_names, ]
}
add_tally <- function(x, wt = NULL, sort = FALSE, name = NULL) {
wt <- deparse_var(wt)
n <- tally_n(x, wt)
name <- check_name(x, name)
res <- do.call(mutate, set_names(list(x, as.name(n)), c(".data", name)))
if (isTRUE(sort)) {
do.call(arrange, list(res, call("desc", as.name(name))))
} else {
res
}
}
tally_n <- function(x, wt) {
if (is.null(wt) && "n" %in% colnames(x)) {
message("Using `n` as weighting variable")
wt <- "n"
}
context$.data <- x
on.exit(rm(list = ".data", envir = context))
if (is.null(wt)) {
"n()"
} else {
paste0("sum(", wt, ", na.rm = TRUE)")
}
}
check_name <- function(df, name) {
if (is.null(name)) {
if ("n" %in% colnames(df)) {
stop(
"Column 'n' is already present in output\n",
"* Use `name = \"new_name\"` to pick a new name"
)
}
return("n")
}
if (!is.character(name) || length(name) != 1) {
stop("`name` must be a single string")
}
name
}
desc <- function(x) -xtfrm(x)
select_env <- new.env()
peek_vars <- function() {
get(".col_names", envir = select_env)
}
context <- new.env()
n <- function() {
do.call(nrow, list(quote(.data)), envir = context)
}
filter <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
filter.grouped_data(.data, ...)
} else {
filter.default(.data, ...)
}
}
filter.default <- function(.data, ...) {
conditions <- paste(deparse_dots(...), collapse = " & ")
context$.data <- .data
on.exit(rm(.data, envir = context))
.data[do.call(with, list(.data, str2lang(unname(conditions)))), ]
}
filter.grouped_data <- function(.data, ...) {
rows <- rownames(.data)
res <- apply_grouped_function(.data, "filter", ...)
res[rows[rows %in% rownames(res)], ]
}
group_by <- function(.data, ..., .add = FALSE) {
check_is_dataframe(.data)
pre_groups <- get_groups(.data)
groups <- deparse_dots(...)
if (isTRUE(.add)) groups <- unique(c(pre_groups, groups))
unknown <- !(groups %in% colnames(.data))
if (any(unknown)) stop("Invalid groups: ", groups[unknown])
structure(.data, class = c("grouped_data", class(.data)), groups = groups)
}
ungroup <- function(x, ...) {
check_is_dataframe(x)
rm_groups <- deparse_dots(...)
groups <- attr(x, "groups")
if (length(rm_groups) == 0L) rm_groups <- groups
attr(x, "groups") <- groups[!(groups %in% rm_groups)]
if (length(attr(x, "groups")) == 0L) {
attr(x, "groups") <- NULL
class(x) <- class(x)[!(class(x) %in% "grouped_data")]
}
x
}
get_groups <- function(x) {
attr(x, "groups", exact = TRUE)
}
has_groups <- function(x) {
groups <- get_groups(x)
if (is.null(groups)) FALSE else TRUE
}
set_groups <- function(x, groups) {
attr(x, "groups") <- groups
x
}
apply_grouped_function <- function(.data, fn, ...) {
groups <- get_groups(.data)
grouped <- split_into_groups(.data, groups)
res <- do.call(rbind, unname(lapply(grouped, fn, ...)))
if (any(groups %in% colnames(res))) {
class(res) <- c("grouped_data", class(res))
attr(res, "groups") <- groups[groups %in% colnames(res)]
}
res
}
split_into_groups <- function(.data, groups) {
class(.data) <- "data.frame"
group_factors <- lapply(groups, function(x, .data) as.factor(.data[, x]), .data)
res <- split(x = .data, f = group_factors)
res
}
print.grouped_data <- function(x, ..., digits = NULL, quote = FALSE, right = TRUE, row.names = TRUE, max = NULL) {
class(x) <- "data.frame"
print(x, ..., digits = digits, quote = quote, right = right, row.names = row.names, max = max)
cat("\nGroups: ", paste(attr(x, "groups", exact = TRUE), collapse = ", "), "\n\n")
}
if_else <- function(condition, true, false, missing = NULL) {
if (!is.logical(condition)) stop("`condition` must be a logical vector.")
cls_true <- class(true)
cls_false <- class(false)
cls_missing <- class(missing)
if (!identical(cls_true, cls_false)) {
stop("The class of `true` <", class(true), "> is not the same as the class of `false` <", class(false), ">")
}
if (!is.null(missing) && !identical(cls_true, cls_missing)) {
stop("`missing` must be a ", cls_true, " vector, not a ", cls_missing, " vector.")
}
res <- ifelse(condition, true, false)
if (!is.null(missing)) res[is.na(res)] <- missing
attributes(res) <- attributes(true)
res
}
inner_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
join_worker(x = x, y = y, by = by, suffix = suffix, sort = FALSE)
}
left_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
join_worker(x = x, y = y, by = by, suffix = suffix, all.x = TRUE)
}
right_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
join_worker(x = x, y = y, by = by, suffix = suffix, all.y = TRUE)
}
full_join <- function(x, y, by = NULL, suffix = c(".x", ".y")) {
join_worker(x = x, y = y, by = by, suffix = suffix, all = TRUE)
}
join_worker <- function(x, y, by = NULL, suffix = c(".x", ".y"), ...) {
x[, ".join_id"] <- seq_len(nrow(x))
if (is.null(by)) {
by <- intersect(names(x), names(y))
join_message(by)
merged <- merge(x = x, y = y, by = by, suffixes = suffix, ...)[, union(names(x), names(y))]
} else if (is.null(names(by))) {
merged <- merge(x = x, y = y, by = by, suffixes = suffix, ...)
} else {
merged <- merge(x = x, y = y, by.x = names(by), by.y = by, suffixes = suffix, ...)
}
merged <- merged[order(merged[, ".join_id"]), colnames(merged) != ".join_id"]
rownames(merged) <- NULL
merged
}
join_message <- function(by) {
if (length(by) > 1L) {
message("Joining, by = c(\"", paste0(by, collapse = "\", \""), "\")\n", sep = "")
} else {
message("Joining, by = \"", by, "\"\n", sep = "")
}
}
anti_join <- function(x, y, by = NULL) {
filter_join_worker(x, y, by, type = "anti")
}
semi_join <- function(x, y, by = NULL) {
filter_join_worker(x, y, by, type = "semi")
}
# filter_join_worker <- function(x, y, by = NULL, type = c("anti", "semi")) {
# type <- match.arg(type, choices = c("anti", "semi"), several.ok = FALSE)
# if (is.null(by)) {
# by <- intersect(names(x), names(y))
# join_message(by)
# }
# rows <- interaction(x[, by]) %in% interaction(y[, by])
# if (type == "anti") rows <- !rows
# res <- x[rows, ]
# rownames(res) <- NULL
# res
# }
lag <- function (x, n = 1L, default = NA) {
if (inherits(x, "ts")) stop("`x` must be a vector, not a `ts` object, do you want `stats::lag()`?")
if (length(n) != 1L || !is.numeric(n) || n < 0L) stop("`n` must be a nonnegative integer scalar")
if (n == 0L) return(x)
tryCatch(
storage.mode(default) <- typeof(x),
warning = function(w) {
stop("Cannot convert `default` <", typeof(default), "> to `x` <", typeof(x), ">")
}
)
xlen <- length(x)
n <- pmin(n, xlen)
res <- c(rep(default, n), x[seq_len(xlen - n)])
attributes(res) <- attributes(x)
res
}
lead <- function (x, n = 1L, default = NA) {
if (length(n) != 1L || !is.numeric(n) || n < 0L) stop("n must be a nonnegative integer scalar")
if (n == 0L) return(x)
tryCatch(
storage.mode(default) <- typeof(x),
warning = function(w) {
stop("Cannot convert `default` <", typeof(default), "> to `x` <", typeof(x), ">")
}
)
xlen <- length(x)
n <- pmin(n, xlen)
res <- c(x[-seq_len(n)], rep(default, n))
attributes(res) <- attributes(x)
res
}
mutate <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
mutate.grouped_data(.data, ...)
} else {
mutate.default(.data, ...)
}
}
mutate.default <- function(.data, ...) {
conditions <- deparse_dots(...)
cond_names <- names(conditions)
unnamed <- which(nchar(cond_names) == 0L)
if (is.null(cond_names)) {
names(conditions) <- conditions
} else if (length(unnamed) > 0L) {
names(conditions)[unnamed] <- conditions[unnamed]
}
not_matched <- names(conditions)[!names(conditions) %in% names(.data)]
.data[, not_matched] <- NA
context$.data <- .data
on.exit(rm(.data, envir = context))
for (i in seq_along(conditions)) {
.data[, names(conditions)[i]] <- do.call(with, list(.data, str2lang(unname(conditions)[i])))
}
.data
}
mutate.grouped_data <- function(.data, ...) {
rows <- rownames(.data)
res <- apply_grouped_function(.data, "mutate", ...)
res[rows, ]
}
n_distinct <- function(..., na.rm = FALSE) {
res <- c(...)
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))
}
`%>%` <- function(lhs, rhs) {
lhs <- substitute(lhs)
rhs <- substitute(rhs)
eval(as.call(c(rhs[[1L]], lhs, as.list(rhs[-1L]))), envir = parent.frame())
}
pull <- function(.data, var = -1) {
var_deparse <- deparse_var(var)
col_names <- colnames(.data)
if (!(var_deparse %in% col_names) & grepl("^[[:digit:]]+L|[[:digit:]]", var_deparse)) {
var <- as.integer(gsub("L", "", var_deparse))
var <- if_else(var < 1L, rev(col_names)[abs(var)], col_names[var])
} else if (var_deparse %in% col_names) {
var <- var_deparse
}
.data[, var]
}
relocate <- function(.data, ..., .before = NULL, .after = NULL) {
check_is_dataframe(.data)
data_names <- colnames(.data)
col_pos <- select_positions(.data, ...)
.before <- deparse_var(.before)
.after <- deparse_var(.after)
has_before <- !is.null(.before)
has_after <- !is.null(.after)
if (has_before && has_after) {
stop("You must supply only one of `.before` and `.after`")
} else if (has_before) {
where <- min(match(.before, data_names))
col_pos <- c(setdiff(col_pos, where), where)
} else if (has_after) {
where <- max(match(.after, data_names))
col_pos <- c(where, setdiff(col_pos, where))
} else {
where <- 1L
col_pos <- union(col_pos, where)
}
lhs <- setdiff(seq(1L, where - 1L), col_pos)
rhs <- setdiff(seq(where + 1L, ncol(.data)), col_pos)
col_pos <- unique(c(lhs, col_pos, rhs))
col_pos <- col_pos[col_pos <= length(data_names)]
res <- .data[col_pos]
if (has_groups(.data)) res <- set_groups(res, get_groups(.data))
res
}
rename <- function(.data, ...) {
check_is_dataframe(.data)
new_names <- names(deparse_dots(...))
if (length(new_names) == 0L) {
warning("You didn't give any new names")
return(.data)
}
col_pos <- select_positions(.data, ...)
old_names <- colnames(.data)[col_pos]
new_names_zero <- nchar(new_names) == 0L
if (any(new_names_zero)) {
warning("You didn't provide new names for: ", paste0("`", old_names[new_names_zero], collapse = ", "), "`")
new_names[new_names_zero] <- old_names[new_names_zero]
}
colnames(.data)[col_pos] <- new_names
.data
}
rownames_to_column <- function(.data, var = "rowname") {
check_is_dataframe(.data)
col_names <- colnames(.data)
if (var %in% col_names) stop("Column `", var, "` already exists in `.data`")
.data[, var] <- rownames(.data)
rownames(.data) <- NULL
.data[, c(var, setdiff(col_names, var))]
}
select <- function(.data, ...) {
map <- names(deparse_dots(...))
col_pos <- select_positions(.data, ..., group_pos = TRUE)
res <- .data[, col_pos, drop = FALSE]
to_map <- nchar(map) > 0L
colnames(res)[to_map] <- map[to_map]
if (has_groups(.data)) res <- set_groups(res, get_groups(.data))
res
}
starts_with <- function(match, ignore.case = TRUE, vars = peek_vars()) {
grep(pattern = paste0("^", paste0(match, collapse = "|^")), x = vars, ignore.case = ignore.case)
}
ends_with <- function(match, ignore.case = TRUE, vars = peek_vars()) {
grep(pattern = paste0(paste0(match, collapse = "$|"), "$"), x = vars, ignore.case = ignore.case)
}
contains <- function(match, ignore.case = TRUE, vars = peek_vars()) {
matches <- lapply(
match,
function(x) {
if (isTRUE(ignore.case)) {
match_u <- toupper(x)
match_l <- tolower(x)
pos_u <- grep(pattern = match_u, x = toupper(vars), fixed = TRUE)
pos_l <- grep(pattern = match_l, x = tolower(vars), fixed = TRUE)
unique(c(pos_l, pos_u))
} else {
grep(pattern = x, x = vars, fixed = TRUE)
}
}
)
unique(matches)
}
matches <- function(match, ignore.case = TRUE, perl = FALSE, vars = peek_vars()) {
grep(pattern = match, x = vars, ignore.case = ignore.case, perl = perl)
}
num_range <- function(prefix, range, width = NULL, vars = peek_vars()) {
if (!is.null(width)) {
range <- sprintf(paste0("%0", width, "d"), range)
}
find <- paste0(prefix, range)
if (any(duplicated(vars))) {
stop("Column names must be unique")
} else {
x <- match(find, vars)
x[!is.na(x)]
}
}
all_of <- function(x, vars = peek_vars()) {
x_ <- !x %in% vars
if (any(x_)) {
which_x_ <- which(x_)
if (length(which_x_) == 1L) {
stop("The column ", x[which_x_], " does not exist.")
} else {
stop("The columns ", paste(x[which_x_], collapse = ", "), " do not exist.")
}
} else {
which(vars %in% x)
}
}
any_of <- function(x, vars = peek_vars()) {
which(vars %in% x)
}
everything <- function(vars = peek_vars()) {
seq_along(vars)
}
last_col <- function(offset = 0L, vars = peek_vars()) {
if (!is_wholenumber(offset)) stop("`offset` must be an integer")
n <- length(vars)
if (offset && n <= offset) {
stop("`offset` must be smaller than the number of `vars`")
} else if (n == 0) {
stop("Can't select last column when `vars` is empty")
} else {
n - offset
}
}
select_positions <- function(.data, ..., group_pos = FALSE) {
cols <- eval(substitute(alist(...)))
data_names <- colnames(.data)
select_env$.col_names <- data_names
on.exit(rm(list = ".col_names", envir = select_env))
exec_env <- parent.frame(2L)
pos <- unlist(lapply(cols, eval_expr, exec_env = exec_env))
if (isTRUE(group_pos)) {
groups <- get_groups(.data)
missing_groups <- !(groups %in% cols)
if (any(missing_groups)) {
message("Adding missing grouping variables: `", paste(groups[missing_groups], collapse = "`, `"), "`")
pos <- c(match(groups[missing_groups], data_names), pos)
}
}
unique(pos)
}
eval_expr <- function(x, exec_env) {
type <- typeof(x)
switch(
type,
"integer" = x,
"double" = as.integer(x),
"character" = select_char(x),
"symbol" = select_symbol(x, exec_env = exec_env),
"language" = eval_call(x),
stop("Expressions of type <", typeof(x), "> cannot be evaluated for use when subsetting.")
)
}
select_char <- function(expr) {
pos <- match(expr, select_env$.col_names)
if (is.na(pos)) stop("Column `", expr, "` does not exist")
pos
}
select_symbol <- function(expr, exec_env) {
res <- try(select_char(as.character(expr)), silent = TRUE)
if (inherits(res, "try-error")) {
res <- tryCatch(
select_char(eval(expr, envir = exec_env)),
error = function(e) stop("Column ", expr, " does not exist.")
)
}
res
}
eval_call <- function(x) {
type <- as.character(x[[1]])
switch(
type,
`:` = select_seq(x),
`!` = select_negate(x),
`-` = select_minus(x),
`c` = select_c(x),
`(` = select_bracket(x),
select_context(x)
)
}
select_seq <- function(expr) {
x <- eval_expr(expr[[2]])
y <- eval_expr(expr[[3]])
x:y
}
select_negate <- function(expr) {
x <- if (is_negated_colon(expr)) {
expr <- call(":", expr[[2]][[2]], expr[[2]][[3]][[2]])
eval_expr(expr)
} else {
eval_expr(expr[[2]])
}
x * -1L
}
is_negated_colon <- function(expr) {
expr[[1]] == "!" && length(expr[[2]]) > 1L && expr[[2]][[1]] == ":" && expr[[2]][[3]][[1]] == "!"
}
select_minus <- function(expr) {
x <- eval_expr(expr[[2]])
x * -1L
}
select_c <- function(expr) {
lst_expr <- as.list(expr)
lst_expr[[1]] <- NULL
unlist(lapply(lst_expr, eval_expr))
}
select_bracket <- function(expr) {
eval_expr(expr[[2]])
}
select_context <- function(expr) {
eval(expr, envir = context$.data)
}
slice <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
slice.grouped_data(.data, ...)
} else {
slice.default(.data, ...)
}
}
slice.default <- function(.data, ...) {
rows <- c(...)
stopifnot(is.numeric(rows) | is.integer(rows))
if (all(rows > 0L)) rows <- rows[rows <= nrow(.data)]
.data[rows, ]
}
slice.grouped_data <- function(.data, ...) {
apply_grouped_function(.data, "slice", ...)
}
summarise <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
summarise.grouped_data(.data, ...)
} else {
summarise.default(.data, ...)
}
}
summarise.default <- function(.data, ...) {
fns <- vapply(substitute(...()), deparse, NA_character_)
context$.data <- .data
on.exit(rm(.data, envir = context))
if (has_groups(.data)) {
group <- unique(.data[, get_groups(.data), drop = FALSE])
if (nrow(group) == 0L) return(NULL)
}
res <- lapply(fns, function(x) do.call(with, list(.data, str2lang(x))))
res <- as.data.frame(res)
fn_names <- names(fns)
colnames(res) <- if (is.null(fn_names)) fns else fn_names
if (has_groups(.data)) res <- cbind(group, res)
res
}
summarise.grouped_data <- function(.data, ...) {
groups <- get_groups(.data)
res <- apply_grouped_function(.data, "summarise", ...)
res <- res[do.call(order, lapply(groups, function(x) res[, x])), ]
rownames(res) <- NULL
res
}
summarize <- summarise
summarize.default <- summarise.default
summarize.grouped_data <- summarise.grouped_data
transmute <- function(.data, ...) {
check_is_dataframe(.data)
if ("grouped_data" %in% class(.data)) {
transmute.grouped_data(.data, ...)
} else {
transmute.default(.data, ...)
}
}
transmute.default <- function(.data, ...) {
conditions <- deparse_dots(...)
mutated <- mutate(.data, ...)
mutated[, names(conditions), drop = FALSE]
}
transmute.grouped_data <- function(.data, ...) {
rows <- rownames(.data)
res <- apply_grouped_function(.data, "transmute", ...)
res[rows, ]
}
deparse_dots <- function(...) {
vapply(substitute(...()), deparse, NA_character_)
}
deparse_var <- function(var) {
sub_var <- eval(substitute(substitute(var)), parent.frame())
if (is.symbol(sub_var)) var <- as.character(sub_var)
var
}
check_is_dataframe <- function(.data) {
parent_fn <- all.names(sys.call(-1L), max.names = 1L)
if (!is.data.frame(.data)) stop(parent_fn, " must be given a data.frame")
invisible()
}
is_wholenumber <- function(x) {
x %% 1L == 0L
}
set_names <- function(object = nm, nm) {
names(object) <- nm
object
}
cume_dist <- function(x) {
rank(x, ties.method = "max", na.last = "keep") / sum(!is.na(x))
}
dense_rank <- function(x) {
match(x, sort(unique(x)))
}
min_rank <- function(x) {
rank(x, ties.method = "min", na.last = "keep")
}
ntile <- function (x = row_number(), n) {
if (!missing(x)) x <- row_number(x)
len <- length(x) - sum(is.na(x))
n <- as.integer(floor(n))
if (len == 0L) {
rep(NA_integer_, length(x))
} else {
n_larger <- as.integer(len %% n)
n_smaller <- as.integer(n - n_larger)
size <- len / n
larger_size <- as.integer(ceiling(size))
smaller_size <- as.integer(floor(size))
larger_threshold <- larger_size * n_larger
bins <- if_else(
x <= larger_threshold,
(x + (larger_size - 1L)) / larger_size,
(x + (-larger_threshold + smaller_size - 1L)) / smaller_size + n_larger
)
as.integer(floor(bins))
}
}
percent_rank <- function(x) {
(min_rank(x) - 1) / (sum(!is.na(x)) - 1)
}
row_number <- function(x) {
if (missing(x)) seq_len(n()) else rank(x, ties.method = "first", na.last = "keep")
}

1129
R/aa_helper_pm_functions.R Normal file

File diff suppressed because it is too large Load Diff

242
R/ab.R
View File

@@ -1,30 +1,35 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Transform to antibiotic ID
#' 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 Maturing lifecycle
#' @inheritSection lifecycle Stable Lifecycle
#' @param x character vector to determine to antibiotic ID
#' @param flag_multiple_results 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 logical to indicate whether a progress bar should be printed
#' @param ... arguments passed on to internal functions
#' @rdname as.ab
#' @inheritSection WHOCC WHOCC
@@ -32,13 +37,14 @@
#'
#' All these properties will be searched for the user input. The [as.ab()] can correct for different forms of misspelling:
#'
#' * Wrong spelling of drug names (like "tobramicin" or "gentamycin"), which corrects for most audible similarities such as f/ph, x/ks, c/z/s, t/th, etc.
#' * Wrong spelling of drug names (such as "tobramicin" or "gentamycin"), which corrects for most audible similarities such as f/ph, x/ks, c/z/s, t/th, etc.
#' * Too few or too many vowels or consonants
#' * Switching two characters (like "mreopenem", often the case in clinical data, when doctors typed too fast)
#' * Switching two characters (such as "mreopenem", often the case in clinical data, when doctors typed too fast)
#' * Digitalised paper records, leaving artefacts like 0/o/O (zero and O's), B/8, n/r, etc.
#'
#' Use the [ab_property()] functions to get properties based on the returned antibiotic ID, see Examples.
#' Use the [`ab_*`][ab_property()] functions to get properties based on the returned antibiotic ID, see *Examples*.
#'
#' Note: the [as.ab()] and [`ab_*`][ab_property()] functions may use very long regular expression to match brand names of antimicrobial agents. This may fail on some systems.
#' @section Source:
#' World Health Organization (WHO) Collaborating Centre for Drug Statistics Methodology: \url{https://www.whocc.no/atc_ddd_index/}
#'
@@ -46,11 +52,12 @@
#'
#' European Commission Public Health PHARMACEUTICALS - COMMUNITY REGISTER: \url{http://ec.europa.eu/health/documents/community-register/html/atc.htm}
#' @aliases ab
#' @return Character (vector) with class [`ab`]. Unknown values will return `NA`.
#' @return A [character] [vector] with additional class [`ab`]
#' @seealso
#' * [antibiotics] for the dataframe that is being used to determine ATCs
#' * [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 Read more on our website!
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' # these examples all return "ERY", the ID of erythromycin:
@@ -75,7 +82,18 @@
#' # they use as.ab() internally:
#' ab_name("J01FA01") # "Erythromycin"
#' ab_name("eryt") # "Erythromycin"
as.ab <- function(x, flag_multiple_results = TRUE, ...) {
#'
#' if (require("dplyr")) {
#'
#' # 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 = TRUE, ...) {
meet_criteria(x, allow_class = c("character", "numeric", "integer", "factor"), allow_NA = TRUE)
meet_criteria(flag_multiple_results, allow_class = "logical", has_length = 1)
meet_criteria(info, allow_class = "logical", has_length = 1)
check_dataset_integrity()
@@ -88,8 +106,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
if (all(toupper(x) %in% antibiotics$ab)) {
# valid AB code, but not yet right class
return(structure(.Data = toupper(x),
class = c("ab", "character")))
return(set_clean_class(toupper(x),
new_class = c("ab", "character")))
}
x_bak <- x
@@ -97,41 +115,32 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
# remove diacritics
x <- iconv(x, from = "UTF-8", to = "ASCII//TRANSLIT")
x <- gsub('"', "", x, fixed = TRUE)
x <- gsub("(specimen|specimen date|specimen_date|spec_date)", "", x, ignore.case = TRUE, perl = TRUE)
x_bak_clean <- x
if (already_regex == FALSE) {
# remove suffices
x_bak_clean <- gsub("_(MIC|RSI|DIS[CK])$", "", x_bak_clean)
# remove disk concentrations, like LVX_NM -> LVX
x_bak_clean <- gsub("_[A-Z]{2}[0-9_.]{0,3}$", "", x_bak_clean)
# remove part between brackets if that's followed by another string
x_bak_clean <- gsub("(.*)+ [(].*[)]", "\\1", x_bak_clean)
# keep only max 1 space
x_bak_clean <- trimws(gsub(" +", " ", x_bak_clean))
# non-character, space or number should be a slash
x_bak_clean <- gsub("[^A-Z0-9 -]", "/", x_bak_clean)
# spaces around non-characters must be removed: amox + clav -> amox/clav
x_bak_clean <- gsub("(.*[A-Z0-9]) ([^A-Z0-9].*)", "\\1\\2", x_bak_clean)
x_bak_clean <- gsub("(.*[^A-Z0-9]) ([A-Z0-9].*)", "\\1\\2", x_bak_clean)
# remove hyphen after a starting "co"
x_bak_clean <- gsub("^CO-", "CO", x_bak_clean)
# replace text 'and' with a slash
x_bak_clean <- gsub(" AND ", "/", x_bak_clean)
x_bak_clean <- generalise_antibiotic_name(x_bak_clean)
}
x <- unique(x_bak_clean)
x <- unique(x_bak_clean) # this means that every x is in fact generalise_antibiotic_name(x)
x_new <- rep(NA_character_, length(x))
x_unknown <- character(0)
note_if_more_than_one_found <- function(found, index, from_text) {
if (initial_search == TRUE & isTRUE(length(from_text) > 1)) {
message(font_blue(paste0("NOTE: more than one result was found for item ", index, ": ",
paste0(ab_name(from_text, tolower = TRUE, initial_search = FALSE), collapse = ", "))))
abnames <- ab_name(from_text, tolower = TRUE, initial_search = FALSE)
if (ab_name(found[1L], language = NULL) %like% "clavulanic acid") {
abnames <- abnames[!abnames == "clavulanic acid"]
}
if (length(abnames) > 1) {
message_("More than one result was found for item ", index, ": ",
paste0(abnames, collapse = ", "))
}
}
found[1L]
}
if (initial_search == TRUE) {
progress <- progress_estimated(n = length(x), n_min = 25) # start if n >= 25
progress <- progress_ticker(n = length(x), n_min = ifelse(isTRUE(info), 25, length(x) + 1)) # start if n >= 25
on.exit(close(progress))
}
@@ -153,11 +162,25 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
if (isTRUE(flag_multiple_results) & x[i] %like% "[ ]") {
from_text <- suppressWarnings(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]])
from_text <- tryCatch(suppressWarnings(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]]),
error = function(e) character(0))
} else {
from_text <- character(0)
}
# old code for phenoxymethylpenicillin (Peni V)
if (x[i] == "PNV") {
x_new[i] <- "PHN"
next
}
# exact name
found <- antibiotics[which(AB_lookup$generalised_name == x[i]), ]$ab
if (length(found) > 0) {
x_new[i] <- found[1L]
next
}
# exact AB code
found <- antibiotics[which(antibiotics$ab == x[i]), ]$ab
if (length(found) > 0) {
@@ -179,15 +202,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
next
}
# exact name
found <- antibiotics[which(toupper(antibiotics$name) == x[i]), ]$ab
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
next
}
# exact LOINC code
loinc_found <- unlist(lapply(antibiotics$loinc,
loinc_found <- unlist(lapply(AB_lookup$generalised_loinc,
function(s) x[i] %in% s))
found <- antibiotics$ab[loinc_found == TRUE]
if (length(found) > 0) {
@@ -196,8 +212,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# exact synonym
synonym_found <- unlist(lapply(antibiotics$synonyms,
function(s) x[i] %in% toupper(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)
@@ -205,8 +221,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# exact abbreviation
abbr_found <- unlist(lapply(antibiotics$abbreviations,
function(a) x[i] %in% toupper(a)))
abbr_found <- unlist(lapply(AB_lookup$generalised_abbreviations,
function(s) x[i] %in% s))
found <- antibiotics$ab[abbr_found == TRUE]
if (length(found) > 0) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -220,44 +236,44 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
x_spelling <- x[i]
if (already_regex == FALSE) {
x_spelling <- gsub("[IY]+", "[IY]+", x_spelling)
x_spelling <- gsub("(C|K|Q|QU|S|Z|X|KS)+", "(C|K|Q|QU|S|Z|X|KS)+", x_spelling)
x_spelling <- gsub("(PH|F|V)+", "(PH|F|V)+", x_spelling)
x_spelling <- gsub("(TH|T)+", "(TH|T)+", x_spelling)
x_spelling <- gsub("A+", "A+", x_spelling)
x_spelling <- gsub("E+", "E+", x_spelling)
x_spelling <- gsub("O+", "O+", x_spelling)
x_spelling <- gsub("[IY]+", "[IY]+", x_spelling, perl = TRUE)
x_spelling <- gsub("(C|K|Q|QU|S|Z|X|KS)+", "(C|K|Q|QU|S|Z|X|KS)+", x_spelling, perl = TRUE)
x_spelling <- gsub("(PH|F|V)+", "(PH|F|V)+", x_spelling, perl = TRUE)
x_spelling <- gsub("(TH|T)+", "(TH|T)+", x_spelling, perl = TRUE)
x_spelling <- gsub("A+", "A+", x_spelling, perl = TRUE)
x_spelling <- gsub("E+", "E+", x_spelling, perl = TRUE)
x_spelling <- gsub("O+", "O+", x_spelling, perl = TRUE)
# allow any ending of -in/-ine and -im/-ime
x_spelling <- gsub("(\\[IY\\]\\+(N|M)|\\[IY\\]\\+(N|M)E\\+)$", "[IY]+(N|M)E*", x_spelling)
x_spelling <- gsub("(\\[IY\\]\\+(N|M)|\\[IY\\]\\+(N|M)E\\+)$", "[IY]+(N|M)E*", x_spelling, perl = TRUE)
# allow any ending of -ol/-ole
x_spelling <- gsub("(O\\+L|O\\+LE\\+)$", "O+LE*", x_spelling)
x_spelling <- gsub("(O\\+L|O\\+LE\\+)$", "O+LE*", x_spelling, perl = TRUE)
# allow any ending of -on/-one
x_spelling <- gsub("(O\\+N|O\\+NE\\+)$", "O+NE*", x_spelling)
x_spelling <- gsub("(O\\+N|O\\+NE\\+)$", "O+NE*", x_spelling, perl = TRUE)
# replace multiple same characters to single one with '+', like "ll" -> "l+"
x_spelling <- gsub("(.)\\1+", "\\1+", x_spelling)
x_spelling <- gsub("(.)\\1+", "\\1+", x_spelling, perl = TRUE)
# replace spaces and slashes with a possibility on both
x_spelling <- gsub("[ /]", "( .*|.*/)", x_spelling)
x_spelling <- gsub("[ /]", "( .*|.*/)", x_spelling, perl = TRUE)
# correct for digital reading text (OCR)
x_spelling <- gsub("[NRD8B]", "[NRD8B]", x_spelling)
x_spelling <- gsub("(O|0)", "(O|0)+", x_spelling)
x_spelling <- gsub("[NRD8B]", "[NRD8B]", x_spelling, perl = TRUE)
x_spelling <- gsub("(O|0)", "(O|0)+", x_spelling, perl = TRUE)
x_spelling <- gsub("++", "+", x_spelling, fixed = TRUE)
}
# try if name starts with it
found <- antibiotics[which(antibiotics$name %like% paste0("^", x_spelling)), ]$ab
found <- antibiotics[which(AB_lookup$generalised_name %like% paste0("^", x_spelling)), ]$ab
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(antibiotics$name %like% paste0(x_spelling, "$")), ]$ab
found <- antibiotics[which(AB_lookup$generalised_name %like% paste0(x_spelling, "$")), ]$ab
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(antibiotics$synonyms,
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) {
@@ -272,7 +288,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
# try by removing all spaces
if (x[i] %like% " ") {
found <- suppressWarnings(as.ab(gsub(" +", "", x[i]), initial_search = FALSE))
found <- suppressWarnings(as.ab(gsub(" +", "", x[i], perl = TRUE), initial_search = FALSE))
if (length(found) > 0 & !is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
next
@@ -281,7 +297,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
# try by removing all spaces and numbers
if (x[i] %like% " " | x[i] %like% "[0-9]") {
found <- suppressWarnings(as.ab(gsub("[ 0-9]", "", x[i]), initial_search = FALSE))
found <- suppressWarnings(as.ab(gsub("[ 0-9]", "", x[i], perl = TRUE), initial_search = FALSE))
if (length(found) > 0 & !is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
next
@@ -289,7 +305,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# 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))) {
y[i] <- ifelse(tolower(y[i]) %in% tolower(translations_file$replacement),
@@ -297,7 +313,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
!isFALSE(translations_file$fixed)), "pattern"],
y[i])
}
y
generalise_antibiotic_name(y)
})[[1]],
collapse = "/")
x_translated_guess <- suppressWarnings(as.ab(x_translated, initial_search = FALSE))
@@ -315,7 +331,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
y_name,
y[i])
}
y
generalise_antibiotic_name(y)
})[[1]],
collapse = "/")
x_translated_guess <- suppressWarnings(as.ab(x_translated, initial_search = FALSE))
@@ -326,7 +342,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
# try by removing all trailing capitals
if (x[i] %like_case% "[a-z]+[A-Z]+$") {
found <- suppressWarnings(as.ab(gsub("[A-Z]+$", "", x[i]), initial_search = FALSE))
found <- suppressWarnings(as.ab(gsub("[A-Z]+$", "", x[i], perl = TRUE), initial_search = FALSE))
if (!is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
next
@@ -334,7 +350,7 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# keep only letters
found <- suppressWarnings(as.ab(gsub("[^A-Z]", "", x[i]), initial_search = FALSE))
found <- suppressWarnings(as.ab(gsub("[^A-Z]", "", x[i], perl = TRUE), initial_search = FALSE))
if (!is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
next
@@ -345,7 +361,8 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
if (isTRUE(flag_multiple_results)) {
found <- from_text[1L]
} else {
found <- suppressWarnings(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]][1L])
found <- tryCatch(suppressWarnings(ab_from_text(x[i], initial_search = FALSE, translate_ab = FALSE)[[1]][1L]),
error = function(e) NA_character_)
}
if (!is.na(found)) {
x_new[i] <- note_if_more_than_one_found(found, i, from_text)
@@ -365,10 +382,10 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# make all consonants facultative
search_str <- gsub("([BCDFGHJKLMNPQRSTVWXZ])", "\\1*", x[i])
search_str <- gsub("([BCDFGHJKLMNPQRSTVWXZ])", "\\1*", x[i], perl = TRUE)
found <- suppressWarnings(as.ab(search_str, initial_search = FALSE, already_regex = TRUE))
# keep at least 4 normal characters
if (nchar(gsub(".\\*", "", search_str)) < 4) {
if (nchar(gsub(".\\*", "", search_str, perl = TRUE)) < 4) {
found <- NA
}
if (!is.na(found)) {
@@ -377,10 +394,10 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
}
# make all vowels facultative
search_str <- gsub("([AEIOUY])", "\\1*", x[i])
search_str <- gsub("([AEIOUY])", "\\1*", x[i], perl = TRUE)
found <- suppressWarnings(as.ab(search_str, initial_search = FALSE, already_regex = TRUE))
# keep at least 5 normal characters
if (nchar(gsub(".\\*", "", search_str)) < 5) {
if (nchar(gsub(".\\*", "", search_str, perl = TRUE)) < 5) {
found <- NA
}
if (!is.na(found)) {
@@ -434,29 +451,29 @@ as.ab <- function(x, flag_multiple_results = TRUE, ...) {
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) {
warning("These ATC codes are not (yet) in the antibiotics data set: ",
paste('"', sort(unique(x_unknown_ATCs)), '"', sep = "", collapse = ", "),
".",
call. = FALSE)
warning_("These ATC codes are not (yet) in the antibiotics data set: ",
paste('"', sort(unique(x_unknown_ATCs)), '"', sep = "", collapse = ", "),
".",
call = FALSE)
}
if (length(x_unknown) > 0) {
warning("These values could not be coerced to a valid antimicrobial ID: ",
paste('"', sort(unique(x_unknown)), '"', sep = "", collapse = ", "),
".",
call. = FALSE)
warning_("These values could not be coerced to a valid antimicrobial ID: ",
paste('"', sort(unique(x_unknown)), '"', sep = "", collapse = ", "),
".",
call = FALSE)
}
x_result <- data.frame(x = x_bak_clean, stringsAsFactors = FALSE) %>%
left_join(data.frame(x = x, x_new = x_new, stringsAsFactors = FALSE), by = "x") %>%
pull(x_new)
x_result <- data.frame(x = x_bak_clean, stringsAsFactors = FALSE) %pm>%
pm_left_join(data.frame(x = x, x_new = x_new, stringsAsFactors = FALSE), by = "x") %pm>%
pm_pull(x_new)
if (length(x_result) == 0) {
x_result <- NA_character_
}
structure(.Data = x_result,
class = c("ab", "character"))
set_clean_class(x_result,
new_class = c("ab", "character"))
}
#' @rdname as.ab
@@ -465,6 +482,18 @@ is.ab <- function(x) {
inherits(x, "ab")
}
# will be exported using s3_register() in R/zzz.R
pillar_shaft.ab <- function(x, ...) {
out <- trimws(format(x))
out[is.na(x)] <- font_na(NA)
create_pillar_column(out, align = "left", min_width = 4)
}
# will be exported using s3_register() in R/zzz.R
type_sum.ab <- function(x, ...) {
"ab"
}
#' @method print ab
#' @export
#' @noRd
@@ -524,3 +553,34 @@ c.ab <- function(x, ...) {
attributes(y) <- attributes(x)
class_integrity_check(y, "antimicrobial code", antibiotics$ab)
}
#' @method unique ab
#' @export
#' @noRd
unique.ab <- function(x, incomparables = FALSE, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
generalise_antibiotic_name <- function(x) {
x <- toupper(x)
# remove suffices
x <- gsub("_(MIC|RSI|DIS[CK])$", "", x, perl = TRUE)
# remove disk concentrations, like LVX_NM -> LVX
x <- gsub("_[A-Z]{2}[0-9_.]{0,3}$", "", x, perl = TRUE)
# remove part between brackets if that's followed by another string
x <- gsub("(.*)+ [(].*[)]", "\\1", x)
# keep only max 1 space
x <- trimws2(gsub(" +", " ", x, perl = TRUE))
# non-character, space or number should be a slash
x <- gsub("[^A-Z0-9 -]", "/", x, perl = TRUE)
# spaces around non-characters must be removed: amox + clav -> amox/clav
x <- gsub("(.*[A-Z0-9]) ([^A-Z0-9].*)", "\\1\\2", x, perl = TRUE)
x <- gsub("(.*[^A-Z0-9]) ([A-Z0-9].*)", "\\1\\2", x, perl = TRUE)
# remove hyphen after a starting "co"
x <- gsub("^CO-", "CO", x, perl = TRUE)
# replace operators with a space
x <- gsub("(/| AND | WITH | W/|[+]|[-])+", " ", x, perl = TRUE)
x
}

View File

@@ -1,38 +1,52 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Antibiotic class selectors
#' Antibiotic Class Selectors
#'
#' Use these selection helpers inside any function that allows [Tidyverse selections](https://tidyselect.r-lib.org/reference/language.html), like `dplyr::select()` or `tidyr::pivot_longer()`. They help to select the columns of antibiotics that are of a specific antibiotic class, without the need to define the columns or antibiotic abbreviations.
#' These functions help to select the columns of antibiotics that are of a specific antibiotic class, without the need to define the columns or antibiotic abbreviations.
#' @inheritSection lifecycle Stable Lifecycle
#' @inheritParams filter_ab_class
#' @details All columns will be searched for known antibiotic names, abbreviations, brand names and codes (ATC, EARS-Net, WHO, etc.). This means that a selector like e.g. [aminoglycosides()] will pick up column names like 'gen', 'genta', 'J01GB03', 'tobra', 'Tobracin', etc.
#' @details \strong{\Sexpr{ifelse(as.double(R.Version()$major) + (as.double(R.Version()$minor) / 10) < 3.2, paste0("NOTE: THESE FUNCTIONS DO NOT WORK ON YOUR CURRENT R VERSION. These functions require R version 3.2 or later - you have ", R.version.string, "."), "")}}
#'
#' These functions only work if the `tidyselect` package is installed, that comes with the `dplyr` package. An error will be thrown if `tidyselect` package is not installed, or if the functions are used outside a function that allows Tidyverse selections like `select()` or `pivot_longer()`.
#' All columns will be searched for known antibiotic names, abbreviations, brand names and codes (ATC, EARS-Net, WHO, etc.) in the [antibiotics] data set. This means that a selector like e.g. [aminoglycosides()] will pick up column names like 'gen', 'genta', 'J01GB03', 'tobra', 'Tobracin', etc.
#' @rdname antibiotic_class_selectors
#' @seealso [filter_ab_class()] for the `filter()` equivalent.
#' @name antibiotic_class_selectors
#' @export
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \dontrun{
#' library(dplyr)
#' # `example_isolates` is a dataset available in the AMR package.
#' # See ?example_isolates.
#'
#' # this will select columns 'IPM' (imipenem) and 'MEM' (meropenem):
#' example_isolates[, c(carbapenems())]
#' # this will select columns 'mo', 'AMK', 'GEN', 'KAN' and 'TOB':
#' example_isolates[, c("mo", aminoglycosides())]
#'
#' if (require("dplyr")) {
#'
#' # this will select columns 'IPM' (imipenem) and 'MEM' (meropenem):
#' example_isolates %>%
@@ -49,16 +63,21 @@
#'
#' # get bug/drug combinations for only macrolides in Gram-positives:
#' example_isolates %>%
#' filter(mo_gramstain(mo) %like% "pos") %>%
#' filter(mo_is_gram_positive()) %>%
#' select(mo, macrolides()) %>%
#' bug_drug_combinations() %>%
#' format()
#'
#'
#' data.frame(irrelevant = "value",
#' data.frame(some_column = "some_value",
#' J01CA01 = "S") %>% # ATC code of ampicillin
#' select(penicillins()) # so the 'J01CA01' column is selected
#'
#' select(penicillins()) # only the 'J01CA01' column will be selected
#'
#'
#' # with dplyr 1.0.0 and higher (that adds 'across()'), this is equal:
#' # (though the row names on the first are more correct)
#' example_isolates %>% filter_carbapenems("R", "all")
#' example_isolates %>% filter(across(carbapenems(), ~. == "R"))
#' }
ab_class <- function(ab_class) {
ab_selector(ab_class, function_name = "ab_class")
@@ -143,14 +162,29 @@ tetracyclines <- function() {
}
ab_selector <- function(ab_class, function_name) {
peek_vars_tidyselect <- import_fn("peek_vars", "tidyselect")
vars_vct <- peek_vars_tidyselect(fn = function_name)
vars_df <- data.frame(as.list(vars_vct))[0, , drop = FALSE]
colnames(vars_df) <- vars_vct
ab_in_data <- suppressMessages(get_column_abx(vars_df))
meet_criteria(ab_class, allow_class = "character", has_length = 1, .call_depth = 1)
meet_criteria(function_name, allow_class = "character", has_length = 1, .call_depth = 1)
if (as.double(R.Version()$major) + (as.double(R.Version()$minor) / 10) < 3.2) {
warning_("antibiotic class selectors such as ", function_name,
"() require R version 3.2 or later - you have ", R.version.string,
call = FALSE)
return(NULL)
}
vars_df <- get_current_data(arg_name = NA, call = -3)
# improve speed here so it will only run once when e.g. in one select call
if (!identical(pkg_env$ab_selector, unique_call_id())) {
ab_in_data <- get_column_abx(vars_df, info = FALSE)
pkg_env$ab_selector <- unique_call_id()
pkg_env$ab_selector_cols <- ab_in_data
} else {
ab_in_data <- pkg_env$ab_selector_cols
}
if (length(ab_in_data) == 0) {
message(font_blue("NOTE: no antimicrobial agents found."))
message_("No antimicrobial agents found.")
return(NULL)
}
@@ -167,14 +201,20 @@ ab_selector <- function(ab_class, function_name) {
}
# get the columns with a group names in the chosen ab class
agents <- ab_in_data[names(ab_in_data) %in% ab_reference$ab]
if (length(agents) == 0) {
message(font_blue(paste0("NOTE: No antimicrobial agents of class ", ab_group,
" found", examples, ".")))
} else {
message(font_blue(paste0("Selecting ", ab_group, ": ",
paste(paste0("`", font_bold(agents, collapse = NULL),
"` (", ab_name(names(agents), tolower = TRUE, language = NULL), ")"),
collapse = ", "))))
if (message_not_thrown_before(function_name)) {
if (length(agents) == 0) {
message_("No antimicrobial agents of class ", ab_group, " found", examples, ".")
} else {
agents_formatted <- paste0("column '", font_bold(agents, collapse = NULL), "'")
agents_names <- ab_name(names(agents), tolower = TRUE, language = NULL)
need_name <- tolower(agents) != tolower(agents_names)
agents_formatted[need_name] <- paste0(agents_formatted[need_name],
" (", agents_names[need_name], ")")
message_("Selecting ", ab_group, ": ", paste(agents_formatted, collapse = ", "),
as_note = FALSE,
extra_indent = nchar(paste0("Selecting ", ab_group, ": ")))
}
remember_thrown_message(function_name)
}
unname(agents)
}

View File

@@ -1,54 +1,58 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Retrieve antimicrobial drug names and doses from clinical text
#' 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 Maturing lifecycle
#' @inheritSection lifecycle Maturing Lifecycle
#' @param text text to analyse
#' @param type type of property to search for, either `"drug"`, `"dose"` or `"administration"`, see *Examples*
#' @param collapse character to pass on to `paste(..., collapse = ...)` to only return one character per element of `text`, see *Examples*
#' @param translate_ab if `type = "drug"`: a column name of the [antibiotics] data set to translate the antibiotic abbreviations to, using [ab_property()]. Defaults to `FALSE`. Using `TRUE` is equal to using "name".
#' @param thorough_search logical to indicate whether the input must be extensively searched for misspelling and other faulty input values. Setting this to `TRUE` will take considerably more time than when using `FALSE`. At default, it will turn `TRUE` when all input elements contain a maximum of three words.
#' @param ... parameters passed on to [as.ab()]
#' @details This function is also internally used by [as.ab()], although it then only searches for the first drug name and will throw a note if more drug names could have been returned.
#' @param ... arguments passed on to [as.ab()]
#' @details This function is also internally used by [as.ab()], although it then only searches for the first drug name and will throw a note if more drug names could have been returned. Note: the [as.ab()] function may use very long regular expression to match brand names of antimicrobial agents. This may fail on some systems.
#'
#' ## Parameter `type`
#' ## Argument `type`
#' At default, the function will search for antimicrobial drug names. All text elements will be searched for official names, ATC codes and brand names. As it uses [as.ab()] internally, it will correct for misspelling.
#'
#' With `type = "dose"` (or similar, like "dosing", "doses"), all text elements will be searched for numeric values that are higher than 100 and do not resemble years. The output will be numeric. It supports any unit (g, mg, IE, etc.) and multiple values in one clinical text, see *Examples*.
#'
#' With `type = "administration"` (or abbreviations, like "admin", "adm"), all text elements will be searched for a form of drug administration. It supports the following forms (including common abbreviations): buccal, implant, inhalation, instillation, intravenous, nasal, oral, parenteral, rectal, sublingual, transdermal and vaginal. Abbreviations for oral (such as 'po', 'per os') will become "oral", all values for intravenous (such as 'iv', 'intraven') will become "iv". It supports multiple values in one clinical text, see *Examples*.
#'
#' ## Parameter `collapse`
#' ## Argument `collapse`
#' Without using `collapse`, this function will return a [list]. This can be convenient to use e.g. inside a `mutate()`):\cr
#' `df %>% mutate(abx = ab_from_text(clinical_text))`
#'
#' The returned AB codes can be transformed to official names, groups, etc. with all [ab_property()] functions like [ab_name()] and [ab_group()], or by using the `translate_ab` parameter.
#' The returned AB codes can be transformed to official names, groups, etc. with all [`ab_*`][ab_property()] functions such as [ab_name()] and [ab_group()], or by using the `translate_ab` argument.
#'
#' With using `collapse`, this function will return a [character]:\cr
#' `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!
#' @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:
@@ -59,7 +63,7 @@
#' ab_from_text("500 mg amoxi po and 400mg cipro iv", type = "admin")
#'
#' ab_from_text("500 mg amoxi po and 400mg cipro iv", collapse = ", ")
#'
#' \donttest{
#' # if you want to know which antibiotic groups were administered, do e.g.:
#' abx <- ab_from_text("500 mg amoxi po and 400mg cipro iv")
#' ab_group(abx[[1]])
@@ -82,22 +86,28 @@
#' collapse = "|"))
#'
#' }
#' }
ab_from_text <- function(text,
type = c("drug", "dose", "administration"),
collapse = NULL,
translate_ab = FALSE,
thorough_search = NULL,
...) {
if (missing(type)) {
type <- type[1L]
}
meet_criteria(text)
meet_criteria(type, allow_class = "character", has_length = 1)
meet_criteria(collapse, has_length = 1, allow_NULL = TRUE)
meet_criteria(translate_ab, allow_NULL = FALSE) # get_translate_ab() will be more informative about what's allowed
meet_criteria(thorough_search, allow_class = "logical", has_length = 1, allow_NULL = TRUE)
type <- tolower(trimws(type))
stop_if(length(type) != 1, "`type` must be of length 1")
text <- tolower(as.character(text))
text_split_all <- strsplit(text, "[ ;.,:\\|]")
progress <- progress_estimated(n = length(text_split_all), n_min = 5)
progress <- progress_ticker(n = length(text_split_all), n_min = 5)
on.exit(close(progress))
if (type %like% "(drug|ab|anti)") {
@@ -105,7 +115,7 @@ ab_from_text <- function(text,
translate_ab <- get_translate_ab(translate_ab)
if (isTRUE(thorough_search) |
(isTRUE(is.null(thorough_search)) & max(sapply(text_split_all, length), na.rm = TRUE) <= 3)) {
(isTRUE(is.null(thorough_search)) & max(vapply(FUN.VALUE = double(1), text_split_all, length), na.rm = TRUE) <= 3)) {
text_split_all <- text_split_all[nchar(text_split_all) >= 4 & grepl("[a-z]+", text_split_all)]
result <- lapply(text_split_all, function(text_split) {
progress$tick()
@@ -193,7 +203,7 @@ ab_from_text <- function(text,
# collapse text if needed
if (!is.null(collapse)) {
result <- sapply(result, function(x) {
result <- vapply(FUN.VALUE = character(1), result, function(x) {
if (length(x) == 1 & all(is.na(x))) {
NA_character_
} else {

View File

@@ -1,36 +1,40 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Property of an antibiotic
#' 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
#' @inheritSection lifecycle Stable Lifecycle
#' @param x any (vector of) text that can be coerced to a valid antibiotic code with [as.ab()]
#' @param tolower 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
#' @param language language of the returned text, defaults to system language (see [get_locale()]) and can also be set with `getOption("AMR_locale")`. Use `language = NULL` or `language = ""` to prevent translation.
#' @param administration way of administration, either `"oral"` or `"iv"`
#' @param units a logical to indicate whether the units instead of the DDDs itself must be returned, see Examples
#' @param units a logical to indicate whether the units instead of the DDDs itself must be returned, see *Examples*
#' @param open browse the URL using [utils::browseURL()]
#' @param ... other parameters passed on to [as.ab()]
#' @param ... other arguments passed on to [as.ab()]
#' @details All output will be [translate]d where possible.
#'
#' The function [ab_url()] will return the direct URL to the official WHO website. A warning will be returned if the required ATC code is not available.
@@ -38,13 +42,14 @@
#' @rdname ab_property
#' @name ab_property
#' @return
#' - An [`integer`] in case of [ab_cid()]
#' - A named [`list`] in case of [ab_info()] and multiple [ab_synonyms()]/[ab_tradenames()]
#' - A [`double`] in case of [ab_ddd()]
#' - A [`character`] in all other cases
#' - An [integer] in case of [ab_cid()]
#' - A named [list] in case of [ab_info()] and multiple [ab_synonyms()]/[ab_tradenames()]
#' - A [double] in case of [ab_ddd()]
#' - A [character] in all other cases
#' @export
#' @seealso [antibiotics]
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # all properties:
#' ab_name("AMX") # "Amoxicillin"
@@ -84,6 +89,10 @@
#' ab_atc("cephthriaxone")
#' ab_atc("seephthriaaksone")
ab_name <- function(x, language = get_locale(), tolower = FALSE, ...) {
meet_criteria(x, allow_NA = TRUE)
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)
if (tolower == TRUE) {
# use perl to only transform the first character
@@ -97,18 +106,21 @@ ab_name <- function(x, language = get_locale(), tolower = FALSE, ...) {
#' @aliases ATC
#' @export
ab_atc <- function(x, ...) {
meet_criteria(x, allow_NA = TRUE)
ab_validate(x = x, property = "atc", ...)
}
#' @rdname ab_property
#' @export
ab_cid <- function(x, ...) {
meet_criteria(x, allow_NA = TRUE)
ab_validate(x = x, property = "cid", ...)
}
#' @rdname ab_property
#' @export
ab_synonyms <- function(x, ...) {
meet_criteria(x, allow_NA = TRUE)
syns <- ab_validate(x = x, property = "synonyms", ...)
names(syns) <- x
if (length(syns) == 1) {
@@ -121,30 +133,38 @@ ab_synonyms <- function(x, ...) {
#' @rdname ab_property
#' @export
ab_tradenames <- function(x, ...) {
meet_criteria(x, allow_NA = TRUE)
ab_synonyms(x, ...)
}
#' @rdname ab_property
#' @export
ab_group <- function(x, language = get_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)
}
#' @rdname ab_property
#' @export
ab_atc_group1 <- function(x, language = get_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)
}
#' @rdname ab_property
#' @export
ab_atc_group2 <- function(x, language = get_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)
}
#' @rdname ab_property
#' @export
ab_loinc <- function(x, ...) {
meet_criteria(x, allow_NA = TRUE)
loincs <- ab_validate(x = x, property = "loinc", ...)
names(loincs) <- x
if (length(loincs) == 1) {
@@ -157,7 +177,10 @@ ab_loinc <- function(x, ...) {
#' @rdname ab_property
#' @export
ab_ddd <- function(x, administration = "oral", units = FALSE, ...) {
stop_ifnot(administration %in% c("oral", "iv"), "`administration` must be 'oral' or 'iv'")
meet_criteria(x, allow_NA = TRUE)
meet_criteria(administration, is_in = c("oral", "iv"), has_length = 1)
meet_criteria(units, allow_class = "logical", has_length = 1)
ddd_prop <- administration
if (units == TRUE) {
ddd_prop <- paste0(ddd_prop, "_units")
@@ -170,8 +193,11 @@ ab_ddd <- function(x, administration = "oral", units = FALSE, ...) {
#' @rdname ab_property
#' @export
ab_info <- function(x, language = get_locale(), ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.ab(x, ...)
base::list(ab = as.character(x),
list(ab = as.character(x),
atc = ab_atc(x),
cid = ab_cid(x),
name = ab_name(x, language = language),
@@ -189,6 +215,9 @@ ab_info <- function(x, language = get_locale(), ...) {
#' @rdname ab_property
#' @export
ab_url <- function(x, open = FALSE, ...) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(open, allow_class = "logical", has_length = 1)
ab <- as.ab(x = x, ... = ...)
u <- paste0("https://www.whocc.no/atc_ddd_index/?code=", ab_atc(ab), "&showdescription=no")
u[is.na(ab_atc(ab))] <- NA_character_
@@ -196,12 +225,12 @@ ab_url <- function(x, open = FALSE, ...) {
NAs <- ab_name(ab, tolower = TRUE, language = NULL)[!is.na(ab) & is.na(ab_atc(ab))]
if (length(NAs) > 0) {
warning("No ATC code available for ", paste0(NAs, collapse = ", "), ".")
warning_("No ATC code available for ", paste0(NAs, collapse = ", "), ".")
}
if (open == TRUE) {
if (length(u) > 1 & !is.na(u[1L])) {
warning("only the first URL will be opened, as `browseURL()` only suports one string.")
warning_("Only the first URL will be opened, as `browseURL()` only suports one string.")
}
if (!is.na(u[1L])) {
utils::browseURL(u[1L])
@@ -213,10 +242,9 @@ ab_url <- function(x, open = FALSE, ...) {
#' @rdname ab_property
#' @export
ab_property <- function(x, property = "name", language = get_locale(), ...) {
stop_if(length(property) != 1L, "'property' must be of length 1.")
stop_ifnot(property %in% colnames(antibiotics),
"invalid property: '", property, "' - use a column name of the `antibiotics` data set")
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)
}
@@ -224,18 +252,18 @@ ab_validate <- function(x, property, ...) {
check_dataset_integrity()
# try to catch an error when inputting an invalid parameter
# 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))
x_bak <- x
if (!all(x %in% antibiotics[, property])) {
x <- data.frame(ab = as.ab(x, ...), stringsAsFactors = FALSE) %>%
left_join(antibiotics, by = "ab") %>%
pull(property)
x <- data.frame(ab = as.ab(x, ...), stringsAsFactors = FALSE) %pm>%
pm_left_join(antibiotics, by = "ab") %pm>%
pm_pull(property)
}
if (property == "ab") {
return(structure(x, class = property))
return(set_clean_class(x, new_class = c("ab", "character")))
} else if (property == "cid") {
return(as.integer(x))
} else if (property %like% "ddd") {

92
R/age.R
View File

@@ -1,35 +1,41 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Age in years of individuals
#' 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
#' @inheritSection lifecycle Stable Lifecycle
#' @param x date(s), will be coerced with [as.POSIXlt()]
#' @param reference reference date(s) (defaults to today), will be coerced with [as.POSIXlt()] and cannot be lower than `x`
#' @param reference reference date(s) (defaults to today), will be coerced with [as.POSIXlt()]
#' @param exact a logical to indicate whether age calculation should be exact, i.e. with decimals. It divides the number of days of [year-to-date](https://en.wikipedia.org/wiki/Year-to-date) (YTD) of `x` by the number of days in the year of `reference` (either 365 or 366).
#' @param na.rm a logical to indicate whether missing values should be removed
#' @param ... arguments passed on to [as.POSIXlt()], such as `origin`
#' @details Ages below 0 will be returned as `NA` with a warning. Ages above 120 will only give a warning.
#' @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!
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' # 10 random birth dates
@@ -40,13 +46,18 @@
#' df$age_exact <- age(df$birth_date, exact = TRUE)
#'
#' df
age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE) {
age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...) {
meet_criteria(x, allow_class = c("character", "Date", "POSIXt"))
meet_criteria(reference, allow_class = c("character", "Date", "POSIXt"))
meet_criteria(exact, allow_class = "logical", has_length = 1)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
if (length(x) != length(reference)) {
stop_if(length(reference) != 1, "`x` and `reference` must be of same length, or `reference` must be of length 1.")
reference <- rep(reference, length(x))
}
x <- as.POSIXlt(x)
reference <- as.POSIXlt(reference)
x <- as.POSIXlt(x, ...)
reference <- as.POSIXlt(reference, ...)
# from https://stackoverflow.com/a/25450756/4575331
years_gap <- reference$year - x$year
@@ -72,10 +83,10 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE) {
if (any(ages < 0, na.rm = TRUE)) {
ages[ages < 0] <- NA
warning("NAs introduced for ages below 0.")
warning_("NAs introduced for ages below 0.", call = TRUE)
}
if (any(ages > 120, na.rm = TRUE)) {
warning("Some ages are above 120.")
warning_("Some ages are above 120.", call = TRUE)
}
if (isTRUE(na.rm)) {
@@ -85,26 +96,26 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE) {
ages
}
#' Split ages into age groups
#' Split Ages into Age Groups
#'
#' Split ages into age groups defined by the `split` parameter. This allows for easier demographic (antimicrobial resistance) analysis.
#' @inheritSection lifecycle Stable lifecycle
#' 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 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
#' @details To split ages, the input for the `split_at` parameter can be:
#' @details To split ages, the input for the `split_at` argument can be:
#'
#' * A numeric vector. A vector of e.g. `c(10, 20)` will split on 0-9, 10-19 and 20+. A value of only `50` will split on 0-49 and 50+.
#' * A numeric vector. A value of e.g. `c(10, 20)` will split `x` on 0-9, 10-19 and 20+. A value of only `50` will split `x` on 0-49 and 50+.
#' The default is to split on young children (0-11), youth (12-24), young adults (25-54), middle-aged adults (55-74) and elderly (75+).
#' * A character:
#' - `"children"` or `"kids"`, equivalent of: `c(0, 1, 2, 4, 6, 13, 18)`. This will split on 0, 1, 2-3, 4-5, 6-12, 13-17 and 18+.
#' - `"elderly"` or `"seniors"`, equivalent of: `c(65, 75, 85)`. This will split on 0-64, 65-74, 75-84, 85+.
#' - `"fives"`, equivalent of: `1:20 * 5`. This will split on 0-4, 5-9, 10-14, ..., 90-94, 95-99, 100+.
#' - `"tens"`, equivalent of: `1:10 * 10`. This will split on 0-9, 10-19, 20-29, ..., 80-89, 90-99, 100+.
#' - `"fives"`, equivalent of: `1:20 * 5`. This will split on 0-4, 5-9, ..., 95-99, 100+.
#' - `"tens"`, equivalent of: `1:10 * 10`. This will split on 0-9, 10-19, ..., 90-99, 100+.
#' @return Ordered [factor]
#' @seealso To determine ages, based on one or more reference dates, use the [age()] function.
#' @export
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' ages <- c(3, 8, 16, 54, 31, 76, 101, 43, 21)
#'
@@ -123,25 +134,28 @@ age <- function(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE) {
#' age_groups(ages, split_at = "fives")
#'
#' # split specifically for children
#' age_groups(ages, "children")
#' # same:
#' age_groups(ages, c(1, 2, 4, 6, 13, 17))
#' age_groups(ages, "children")
#'
#' \dontrun{
#' # resistance of ciprofloxacine per age group
#' library(dplyr)
#' example_isolates %>%
#' filter_first_isolate() %>%
#' filter(mo == as.mo("E. coli")) %>%
#' group_by(age_group = age_groups(age)) %>%
#' select(age_group, CIP) %>%
#' ggplot_rsi(x = "age_group")
#' \donttest{
#' # resistance of ciprofloxacin per age group
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter_first_isolate() %>%
#' filter(mo == as.mo("E. coli")) %>%
#' group_by(age_group = age_groups(age)) %>%
#' select(age_group, CIP) %>%
#' ggplot_rsi(x = "age_group", minimum = 0)
#' }
#' }
age_groups <- function(x, split_at = c(12, 25, 55, 75), na.rm = FALSE) {
stop_ifnot(is.numeric(x), "`x` must be numeric, not ", paste0(class(x), collapse = "/"))
meet_criteria(x, allow_class = c("numeric", "integer"))
meet_criteria(split_at, allow_class = c("numeric", "integer", "character"))
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
if (any(x < 0, na.rm = TRUE)) {
x[x < 0] <- NA
warning("NAs introduced for ages below 0.")
warning_("NAs introduced for ages below 0.", call = TRUE)
}
if (is.character(split_at)) {
split_at <- split_at[1L]
@@ -165,17 +179,17 @@ age_groups <- function(x, split_at = c(12, 25, 55, 75), na.rm = FALSE) {
# turn input values to 'split_at' indices
y <- x
labs <- split_at
lbls <- split_at
for (i in seq_len(length(split_at))) {
y[x >= split_at[i]] <- i
# create labels
labs[i - 1] <- paste0(unique(c(split_at[i - 1], split_at[i] - 1)), collapse = "-")
lbls[i - 1] <- paste0(unique(c(split_at[i - 1], split_at[i] - 1)), collapse = "-")
}
# last category
labs[length(labs)] <- paste0(split_at[length(split_at)], "+")
lbls[length(lbls)] <- paste0(split_at[length(split_at)], "+")
agegroups <- factor(labs[y], levels = labs, ordered = TRUE)
agegroups <- factor(lbls[y], levels = lbls, ordered = TRUE)
if (isTRUE(na.rm)) {
agegroups <- agegroups[!is.na(agegroups)]

42
R/amr.R
View File

@@ -1,33 +1,37 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' The `AMR` Package
#'
#' Welcome to the `AMR` package.
#' @details
#' `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.
#' `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.
#'
#' After installing this package, R knows ~70,000 distinct microbial species and all ~550 antibiotic, antimycotic and antiviral drugs by name and code (including ATC, EARS-NET, LOINC and SNOMED CT), and knows all about valid R/SI and MIC values. It supports any data format, including WHONET/EARS-Net data.
#' After installing this package, \R knows ~70,000 distinct microbial species and all ~550 antibiotic, antimycotic and antiviral drugs by name and code (including ATC, EARS-NET, LOINC and SNOMED CT), and knows all about valid R/SI and MIC values. It supports any data format, including WHONET/EARS-Net data.
#'
#' This package is fully independent of any other R package and works on Windows, macOS and Linux with all versions of R since R-3.0.0 (April 2013). It was designed to work in any setting, including those with very limited resources. It was created for both routine data analysis and academic research at the Faculty of Medical Sciences of the University of Groningen, in collaboration with non-profit organisations Certe Medical Diagnostics and Advice and University Medical Center Groningen. This R package is actively maintained and free software; you can freely use and distribute it for both personal and commercial (but not patent) purposes under the terms of the GNU General Public License version 2.0 (GPL-2), as published by the Free Software Foundation.
#' This package is fully independent of any other \R package and works on Windows, macOS and Linux with all versions of \R since R-3.0.0 (April 2013). It was designed to work in any setting, including those with very limited resources. It was created for both routine data analysis and academic research at the Faculty of Medical Sciences of the University of Groningen, in collaboration with non-profit organisations Certe Medical Diagnostics and Advice and University Medical Center Groningen. This \R package is actively maintained and free software; you can freely use and distribute it for both personal and commercial (but not patent) purposes under the terms of the GNU General Public License version 2.0 (GPL-2), as published by the Free Software Foundation.
#'
#' This package can be used for:
#' - Reference for the taxonomy of microorganisms, since the package contains all microbial (sub)species from the Catalogue of Life and List of Prokaryotic names with Standing in Nomenclature
@@ -38,8 +42,8 @@
#' - Determining multi-drug resistance (MDR) / multi-drug resistant organisms (MDRO)
#' - Calculating (empirical) susceptibility of both mono therapy and combination therapies
#' - Predicting future antimicrobial resistance using regression models
#' - Getting properties for any microorganism (like Gram stain, species, genus or family)
#' - Getting properties for any antibiotic (like name, code of EARS-Net/ATC/LOINC/PubChem, defined daily dose or trade name)
#' - Getting properties for any microorganism (such as Gram stain, species, genus or family)
#' - Getting properties for any antibiotic (such as name, code of EARS-Net/ATC/LOINC/PubChem, defined daily dose or trade name)
#' - Plotting antimicrobial resistance
#' - Applying EUCAST expert rules
#' - Getting SNOMED codes of a microorganism, or getting properties of a microorganism based on a SNOMED code
@@ -47,8 +51,10 @@
#' - Machine reading the EUCAST and CLSI guidelines from 2011-2020 to translate MIC values and disk diffusion diameters to R/SI
#' - Principal component analysis for AMR
#'
#' @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 analysis, the [complete documentation of all functions](https://msberends.github.io/AMR/reference) (which reads a lot easier than here in R) and [an example analysis using WHONET data](https://msberends.github.io/AMR/articles/WHONET.html). As we would like to better understand the backgrounds and needs of our users, please [participate in our survey](https://msberends.github.io/AMR/survey.html)!
#' @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 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). As we would like to better understand the backgrounds and needs of our users, please [participate in our survey](https://msberends.github.io/AMR/survey.html)!
#' @section Contact Us:
#' For suggestions, comments or questions, please contact us at:
#'
@@ -60,9 +66,23 @@
#' Post Office Box 30001 \cr
#' 9700 RB Groningen \cr
#' The Netherlands
#' <https://msberends.github.io/AMR/>
#'
#' If you have found a bug, please file a new issue at: \cr
#' <https://github.com/msberends/AMR/issues>
#' @name AMR
#' @rdname AMR
NULL
#' Plotting for Classes `rsi`, `mic` and `disk`
#'
#' Functions to print classes of the `AMR` package.
#' @inheritSection lifecycle Stable Lifecycle
#' @inheritSection AMR Read more on Our Website!
#' @param ... Arguments passed on to functions
#' @inheritParams base::plot
#' @inheritParams graphics::barplot
#' @name plot
#' @rdname plot
#' @keywords internal
NULL

View File

@@ -1,37 +1,40 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Get ATC properties from WHOCC website
#' Get ATC Properties from WHOCC Website
#'
#' @inheritSection lifecycle Questioning lifecycle
#' @description Gets data from the WHO to determine properties of an ATC (e.g. an antibiotic) like name, defined daily dose (DDD) or standard unit.
#'
#' **This function requires an internet connection.**
#' Gets data from the WHO to determine properties of an 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 or character vector with ATC code(s) of antibiotic(s)
#' @param property property of an ATC code. Valid values are `"ATC"`, `"Name"`, `"DDD"`, `"U"` (`"unit"`), `"Adm.R"`, `"Note"` and `groups`. For this last option, all hierarchical groups of an ATC code will be returned, see Examples.
#' @param administration type of administration when using `property = "Adm.R"`, see Details
#' @param url url of website of the WHO. The sign `%s` can be used as a placeholder for ATC codes.
#' @param ... parameters to pass on to `atc_property`
#' @param property property of an ATC code. Valid values are `"ATC"`, `"Name"`, `"DDD"`, `"U"` (`"unit"`), `"Adm.R"`, `"Note"` and `groups`. For this last option, all hierarchical groups of an ATC code will be returned, see *Examples*.
#' @param administration type of administration when using `property = "Adm.R"`, see *Details*
#' @param url url of website of the WHOCC. The sign `%s` can be used as a placeholder for ATC codes.
#' @param url_vet url of website of the WHOCC for veterinary medicine. The sign `%s` can be used as a placeholder for ATC_vet codes (that all start with "Q").
#' @param ... arguments to pass on to `atc_property`
#' @details
#' Options for parameter `administration`:
#' Options for argument `administration`:
#'
#' - `"Implant"` = Implant
#' - `"Inhal"` = Inhalation
@@ -54,27 +57,32 @@
#' - `"MU"` = million units
#' - `"mmol"` = millimole
#' - `"ml"` = milliliter (e.g. eyedrops)
#'
#' **N.B. This function requires an internet connection and only works if the following packages are installed: `curl`, `rvest`, `xml2`.**
#' @export
#' @rdname atc_online
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @source <https://www.whocc.no/atc_ddd_alterations__cumulative/ddd_alterations/abbrevations/>
#' @examples
#' \dontrun{
#' \donttest{
#' # oral DDD (Defined Daily Dose) of amoxicillin
#' atc_online_property("J01CA04", "DDD", "O")
#'
#' # parenteral DDD (Defined Daily Dose) of amoxicillin
#' atc_online_property("J01CA04", "DDD", "P")
#'
#' atc_online_property("J01CA04", property = "groups") # search hierarchical groups of amoxicillin
#' # [1] "ANTIINFECTIVES FOR SYSTEMIC USE"
#' # [2] "ANTIBACTERIALS FOR SYSTEMIC USE"
#' # [3] "BETA-LACTAM ANTIBACTERIALS, PENICILLINS"
#' # [4] "Penicillins with extended spectrum"
#' }
atc_online_property <- function(atc_code,
property,
administration = "O",
url = "https://www.whocc.no/atc_ddd_index/?code=%s&showdescription=no") {
url = "https://www.whocc.no/atc_ddd_index/?code=%s&showdescription=no",
url_vet = "https://www.whocc.no/atcvet/atcvet_index/?code=%s&showdescription=no") {
meet_criteria(atc_code, allow_class = "character")
meet_criteria(property, allow_class = "character", has_length = 1, is_in = c("ATC", "Name", "DDD", "U", "Adm.R", "Note", "groups"), ignore.case = TRUE)
meet_criteria(administration, allow_class = "character", has_length = 1)
meet_criteria(url, allow_class = "character", has_length = 1, looks_like = "https?://")
meet_criteria(url_vet, allow_class = "character", has_length = 1, looks_like = "https?://")
has_internet <- import_fn("has_internet", "curl")
html_attr <- import_fn("html_attr", "rvest")
@@ -92,28 +100,18 @@ atc_online_property <- function(atc_code,
}
if (!has_internet()) {
message("There appears to be no internet connection.")
message_("There appears to be no internet connection, returning NA.",
add_fn = font_red,
as_note = FALSE)
return(rep(NA, length(atc_code)))
}
stop_if(length(property) != 1L, "`property` must be of length 1")
stop_if(length(administration) != 1L, "`administration` must be of length 1")
# also allow unit as property
if (property %like% "unit") {
property <- "U"
}
# validation of properties
valid_properties <- c("ATC", "Name", "DDD", "U", "Adm.R", "Note", "groups")
valid_properties.bak <- valid_properties
property <- tolower(property)
valid_properties <- tolower(valid_properties)
stop_ifnot(property %in% valid_properties,
"Invalid `property`, use one of ", paste(valid_properties.bak, collapse = ", "))
if (property == "ddd") {
returnvalue <- rep(NA_real_, length(atc_code))
} else if (property == "groups") {
@@ -122,25 +120,31 @@ atc_online_property <- function(atc_code,
returnvalue <- rep(NA_character_, length(atc_code))
}
progress <- progress_estimated(n = length(atc_code), 3)
progress <- progress_ticker(n = length(atc_code), 3)
on.exit(close(progress))
for (i in seq_len(length(atc_code))) {
progress$tick()
atc_url <- sub("%s", atc_code[i], url, fixed = TRUE)
if (atc_code[i] %like% "^Q") {
# veterinary drugs, ATC_vet codes start with a "Q"
atc_url <- url_vet
} else {
atc_url <- url
}
atc_url <- sub("%s", atc_code[i], atc_url, fixed = TRUE)
if (property == "groups") {
tbl <- read_html(atc_url) %>%
html_node("#content") %>%
html_children() %>%
tbl <- read_html(atc_url) %pm>%
html_node("#content") %pm>%
html_children() %pm>%
html_node("a")
# get URLS of items
hrefs <- tbl %>% html_attr("href")
hrefs <- tbl %pm>% html_attr("href")
# get text of items
texts <- tbl %>% html_text()
texts <- tbl %pm>% html_text()
# select only text items where URL like "code="
texts <- texts[grepl("?code=", tolower(hrefs), fixed = TRUE)]
# last one is antibiotics, skip it
@@ -148,16 +152,16 @@ atc_online_property <- function(atc_code,
returnvalue <- c(list(texts), returnvalue)
} else {
tbl <- read_html(atc_url) %>%
html_nodes("table") %>%
html_table(header = TRUE) %>%
tbl <- read_html(atc_url) %pm>%
html_nodes("table") %pm>%
html_table(header = TRUE) %pm>%
as.data.frame(stringsAsFactors = FALSE)
# case insensitive column names
colnames(tbl) <- gsub("^atc.*", "atc", tolower(colnames(tbl)))
if (length(tbl) == 0) {
warning("ATC not found: ", atc_code[i], ". Please check ", atc_url, ".", call. = FALSE)
warning_("ATC not found: ", atc_code[i], ". Please check ", atc_url, ".", call = FALSE)
returnvalue[i] <- NA
next
}
@@ -190,11 +194,13 @@ atc_online_property <- function(atc_code,
#' @rdname atc_online
#' @export
atc_online_groups <- function(atc_code, ...) {
meet_criteria(atc_code, allow_class = "character")
atc_online_property(atc_code = atc_code, property = "groups", ...)
}
#' @rdname atc_online
#' @export
atc_online_ddd <- function(atc_code, ...) {
meet_criteria(atc_code, allow_class = "character")
atc_online_property(atc_code = atc_code, property = "ddd", ...)
}

View File

@@ -1,57 +1,56 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Check availability of columns
#' 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`]
#' @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!
#' @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)
#'
#' \dontrun{
#' library(dplyr)
#' example_isolates %>% availability()
#'
#' example_isolates %>%
#' select_if(is.rsi) %>%
#' availability()
#'
#' example_isolates %>%
#' filter(mo == as.mo("E. coli")) %>%
#' select_if(is.rsi) %>%
#' availability()
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter(mo == as.mo("E. coli")) %>%
#' select_if(is.rsi) %>%
#' availability()
#' }
availability <- function(tbl, width = NULL) {
stop_ifnot(is.data.frame(tbl), "`tbl` must be a data.frame")
x <- base::sapply(tbl, function(x) {
1 - base::sum(base::is.na(x)) / base::length(x)
meet_criteria(tbl, allow_class = "data.frame")
meet_criteria(width, allow_class = "numeric", allow_NULL = TRUE)
x <- vapply(FUN.VALUE = double(1), tbl, function(x) {
1 - sum(is.na(x)) / length(x)
})
n <- base::sapply(tbl, function(x) base::length(x[!base::is.na(x)]))
R <- base::sapply(tbl, function(x) base::ifelse(is.rsi(x), resistance(x, minimum = 0), NA))
n <- vapply(FUN.VALUE = double(1), tbl, function(x) length(x[!is.na(x)]))
R <- vapply(FUN.VALUE = double(1), tbl, function(x) ifelse(is.rsi(x), resistance(x, minimum = 0), NA_real_))
R_print <- character(length(R))
R_print[!is.na(R)] <- percentage(R[!is.na(R)])
R_print[is.na(R)] <- ""
@@ -86,7 +85,8 @@ availability <- function(tbl, width = NULL) {
available = percentage(x),
visual_availabilty = paste0("|", x_chars, x_chars_empty, "|"),
resistant = R_print,
visual_resistance = vis_resistance)
visual_resistance = vis_resistance,
stringsAsFactors = FALSE)
if (length(R[is.na(R)]) == ncol(tbl)) {
df[, 1:3]
} else {

View File

@@ -1,45 +1,47 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Determine bug-drug combinations
#' 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 publicable/printable format, see Examples.
#' @inheritSection lifecycle Stable lifecycle
#' 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 publicable/printable format, see *Examples*.
#' @inheritSection lifecycle Stable Lifecycle
#' @inheritParams eucast_rules
#' @param combine_IR logical to indicate whether values R and I should be summed
#' @param add_ab_group logical to indicate where the group of the antimicrobials must be included as a first column
#' @param remove_intrinsic_resistant logical to indicate that rows with 100% resistance for all tested antimicrobials must be removed from the table
#' @param FUN the function to call on the `mo` column to transform the microorganism IDs, defaults to [mo_shortname()]
#' @param translate_ab a character of length 1 containing column names of the [antibiotics] data set
#' @param remove_intrinsic_resistant logical to indicate that rows and columns with 100% resistance for all tested antimicrobials must be removed from the table
#' @param FUN function to call on the `mo` column to transform the microorganism IDs, defaults to [mo_shortname()]
#' @param translate_ab character of length 1 containing column names of the [antibiotics] data set
#' @param ... arguments passed on to `FUN`
#' @inheritParams rsi_df
#' @inheritParams base::formatC
#' @details The function [format()] calculates the resistance per bug-drug combination. Use `combine_IR = FALSE` (default) to test R vs. S+I and `combine_IR = TRUE` to test R+I vs. S.
#'
#' The language of the output can be overwritten with `options(AMR_locale)`, please see [translate].
#' @export
#' @rdname bug_drug_combinations
#' @return The function [bug_drug_combinations()] returns a [`data.frame`] with columns "mo", "ab", "S", "I", "R" and "total".
#' @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!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \donttest{
#' x <- bug_drug_combinations(example_isolates)
@@ -47,46 +49,49 @@
#' format(x, translate_ab = "name (atc)")
#'
#' # Use FUN to change to transformation of microorganism codes
#' x <- bug_drug_combinations(example_isolates,
#' FUN = mo_gramstain)
#' bug_drug_combinations(example_isolates,
#' FUN = mo_gramstain)
#'
#' x <- bug_drug_combinations(example_isolates,
#' FUN = function(x) ifelse(x == "B_ESCHR_COLI",
#' "E. coli",
#' "Others"))
#' bug_drug_combinations(example_isolates,
#' FUN = function(x) ifelse(x == as.mo("E. coli"),
#' "E. coli",
#' "Others"))
#' }
bug_drug_combinations <- function(x,
col_mo = NULL,
FUN = mo_shortname,
...) {
stop_ifnot(is.data.frame(x), "`x` must be a data frame")
stop_ifnot(any(sapply(x, is.rsi), na.rm = TRUE), "No columns with class <rsi> found. See ?as.rsi.")
meet_criteria(x, allow_class = "data.frame", contains_column_class = "rsi")
meet_criteria(col_mo, allow_class = "character", is_in = colnames(x), has_length = 1, allow_NULL = TRUE)
meet_criteria(FUN, allow_class = "function", has_length = 1)
# try to find columns based on type
# -- mo
if (is.null(col_mo)) {
col_mo <- search_type_in_df(x = x, type = "mo")
stop_if(is.null(col_mo), "`col_mo` must be set")
} else {
stop_ifnot(col_mo %in% colnames(x), "column '", col_mo, "' (`col_mo`) not found")
}
stop_if(is.null(col_mo), "`col_mo` must be set")
x_class <- class(x)
x <- as.data.frame(x, stringsAsFactors = FALSE)
x[, col_mo] <- FUN(x[, col_mo, drop = TRUE])
x <- x[, c(col_mo, names(which(sapply(x, is.rsi)))), drop = FALSE]
x[, col_mo] <- FUN(x[, col_mo, drop = TRUE], ...)
x <- x[, c(col_mo, names(which(vapply(FUN.VALUE = logical(1), x, is.rsi)))), drop = FALSE]
unique_mo <- sort(unique(x[, col_mo, drop = TRUE]))
out <- data.frame(
mo = character(0),
ab = character(0),
S = integer(0),
I = integer(0),
R = integer(0),
total = integer(0))
out <- data.frame(mo = character(0),
ab = character(0),
S = integer(0),
I = integer(0),
R = integer(0),
total = integer(0),
stringsAsFactors = FALSE)
for (i in seq_len(length(unique_mo))) {
# filter on MO group and only select R/SI columns
x_mo_filter <- x[which(x[, col_mo, drop = TRUE] == unique_mo[i]), names(which(sapply(x, is.rsi))), drop = FALSE]
x_mo_filter <- x[which(x[, col_mo, drop = TRUE] == unique_mo[i]), names(which(vapply(FUN.VALUE = logical(1), x, is.rsi))), drop = FALSE]
# turn and merge everything
pivot <- lapply(x_mo_filter, function(x) {
m <- as.matrix(table(x))
@@ -98,11 +103,13 @@ bug_drug_combinations <- function(x,
S = merged$S,
I = merged$I,
R = merged$R,
total = merged$S + merged$I + merged$R)
out <- rbind(out, out_group)
total = merged$S + merged$I + merged$R,
stringsAsFactors = FALSE)
out <- rbind(out, out_group, stringsAsFactors = FALSE)
}
structure(.Data = out, class = c("bug_drug_combinations", x_class))
set_clean_class(out,
new_class = c("bug_drug_combinations", x_class))
}
#' @method format bug_drug_combinations
@@ -119,6 +126,17 @@ format.bug_drug_combinations <- function(x,
decimal.mark = getOption("OutDec"),
big.mark = ifelse(decimal.mark == ",", ".", ","),
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(combine_SI, allow_class = "logical", has_length = 1)
meet_criteria(combine_IR, allow_class = "logical", has_length = 1)
meet_criteria(add_ab_group, allow_class = "logical", has_length = 1)
meet_criteria(remove_intrinsic_resistant, allow_class = "logical", has_length = 1)
meet_criteria(decimal.mark, allow_class = "character", has_length = 1)
meet_criteria(big.mark, allow_class = "character", has_length = 1)
x <- as.data.frame(x, stringsAsFactors = FALSE)
x <- subset(x, total >= minimum)
@@ -149,7 +167,8 @@ format.bug_drug_combinations <- function(x,
remove_NAs <- function(.data) {
cols <- colnames(.data)
.data <- as.data.frame(sapply(.data, function(x) ifelse(is.na(x), "", x), simplify = FALSE))
.data <- as.data.frame(lapply(.data, function(x) ifelse(is.na(x), "", x)),
stringsAsFactors = FALSE)
colnames(.data) <- cols
.data
}
@@ -162,55 +181,63 @@ format.bug_drug_combinations <- function(x,
.data
}
y <- x %>%
y <- x %pm>%
create_var(ab = as.ab(x$ab),
ab_txt = give_ab_name(ab = x$ab, format = translate_ab, language = language)) %>%
group_by(ab, ab_txt, mo) %>%
summarise(isolates = sum(isolates, na.rm = TRUE),
total = sum(total, na.rm = TRUE)) %>%
ungroup()
ab_txt = give_ab_name(ab = x$ab, format = translate_ab, language = language)) %pm>%
pm_group_by(ab, ab_txt, mo) %pm>%
pm_summarise(isolates = sum(isolates, na.rm = TRUE),
total = sum(total, na.rm = TRUE)) %pm>%
pm_ungroup()
y <- y %>%
y <- y %pm>%
create_var(txt = paste0(percentage(y$isolates / y$total, decimal.mark = decimal.mark, big.mark = big.mark),
" (", trimws(format(y$isolates, big.mark = big.mark)), "/",
trimws(format(y$total, big.mark = big.mark)), ")")) %>%
select(ab, ab_txt, mo, txt) %>%
arrange(mo)
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")]
colnames(mo_group) <- c("ab", i)
rownames(mo_group) <- NULL
y <- y %>%
left_join(mo_group, by = "ab")
y <- y %pm>%
pm_left_join(mo_group, by = "ab")
}
y <- y %>%
distinct(ab, .keep_all = TRUE) %>%
select(-mo, -txt) %>%
y <- y %pm>%
pm_distinct(ab, .keep_all = TRUE) %pm>%
pm_select(-mo, -txt) %pm>%
# replace tidyr::pivot_wider() until here
remove_NAs()
select_ab_vars <- function(.data) {
.data[, c("ab_group", "ab_txt", colnames(.data)[!colnames(.data) %in% c("ab_group", "ab_txt", "ab")])]
}
y <- y %>%
create_var(ab_group = ab_group(y$ab, language = language)) %>%
select_ab_vars() %>%
arrange(ab_group, ab_txt)
y <- y %>%
create_var(ab_group = ifelse(y$ab_group != lag(y$ab_group) | is.na(lag(y$ab_group)), y$ab_group, ""))
y <- y %pm>%
create_var(ab_group = ab_group(y$ab, language = language)) %pm>%
select_ab_vars() %pm>%
pm_arrange(ab_group, ab_txt)
y <- y %pm>%
create_var(ab_group = ifelse(y$ab_group != pm_lag(y$ab_group) | is.na(pm_lag(y$ab_group)), y$ab_group, ""))
if (add_ab_group == FALSE) {
y <- y %>%
select(-ab_group) %>%
rename("Drug" = ab_txt)
colnames(y)[1] <- translate_AMR(colnames(y)[1], language = get_locale(), only_unknown = FALSE)
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)
} else {
y <- y %>% rename("Group" = ab_group,
"Drug" = ab_txt)
colnames(y)[1:2] <- translate_AMR(colnames(y)[1:2], language = get_locale(), only_unknown = FALSE)
y <- y %pm>%
pm_rename("Group" = ab_group,
"Drug" = ab_txt)
}
if (!is.null(language)) {
colnames(y) <- translate_AMR(colnames(y), language, only_unknown = FALSE)
}
if (remove_intrinsic_resistant == TRUE) {
y <- y[, !vapply(FUN.VALUE = logical(1), y, function(col) all(col %like% "100", na.rm = TRUE) & !any(is.na(col))), drop = FALSE]
}
rownames(y) <- NULL
@@ -221,7 +248,8 @@ format.bug_drug_combinations <- function(x,
#' @export
print.bug_drug_combinations <- function(x, ...) {
x_class <- class(x)
print(structure(x, class = x_class[x_class != "bug_drug_combinations"]),
print(set_clean_class(x,
new_class = x_class[x_class != "bug_drug_combinations"]),
...)
message(font_blue("NOTE: Use 'format()' on this result to get a publishable/printable format."))
message_("Use 'format()' on this result to get a publishable/printable format.", as_note = FALSE)
}

View File

@@ -1,45 +1,65 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
format_included_data_number <- function(data) {
if (is.data.frame(data)) {
n <- nrow(data)
} else {
n <- length(unique(data))
}
if (n > 10000) {
rounder <- -3 # round on thousands
} else if (n > 1000) {
rounder <- -2 # round on hundreds
} else {
rounder <- -1 # round on tens
}
paste0("~", format(round(n, rounder), decimal.mark = ".", big.mark = ","))
}
#' The Catalogue of Life
#'
#' This package contains the complete taxonomic tree of almost all microorganisms from the authoritative and comprehensive Catalogue of Life.
#' @section Catalogue of Life:
#' \if{html}{\figure{logo_col.png}{options: height=40px style=margin-bottom:5px} \cr}
#' This package contains the complete taxonomic tree of almost all microorganisms (~70,000 species) from the authoritative and comprehensive Catalogue of Life (<http://www.catalogueoflife.org>). The Catalogue of Life is the most comprehensive and authoritative global index of species currently available.
#' This package contains the complete taxonomic tree of almost all microorganisms (~70,000 species) from the authoritative and comprehensive Catalogue of Life (CoL, <http://www.catalogueoflife.org>). The CoL is the most comprehensive and authoritative global index of species currently available. Nonetheless, we supplemented the CoL data with data from the List of Prokaryotic names with Standing in Nomenclature (LPSN, [lpsn.dsmz.de](https://lpsn.dsmz.de)). This supplementation is needed until the [CoL+ project](https://github.com/CatalogueOfLife/general) is finished, which we await.
#'
#' [Click here][catalogue_of_life] for more information about the included taxa. Check which version of the Catalogue of Life was included in this package with [catalogue_of_life_version()].
#' @section Included taxa:
#' [Click here][catalogue_of_life] for more information about the included taxa. Check which versions of the CoL and LSPN were included in this package with [catalogue_of_life_version()].
#' @section Included Taxa:
#' Included are:
#' - All ~61,000 (sub)species from the kingdoms of Archaea, Bacteria, Chromista and Protozoa
#' - All ~8,500 (sub)species from these orders of the kingdom of Fungi: Eurotiales, Microascales, Mucorales, Onygenales, Pneumocystales, Saccharomycetales, Schizosaccharomycetales and Tremellales. 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 (like all species of *Aspergillus*, *Candida*, *Cryptococcus*, *Histplasma*, *Pneumocystis*, *Saccharomyces* and *Trichophyton*).
#' - All ~150 (sub)species from ~100 other relevant genera from the kingdom of Animalia (like *Strongyloides* and *Taenia*)
#' - All ~23,000 previously accepted names of all included (sub)species (these were taxonomically renamed)
#' - 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.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
#'
#' 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/master/data-raw/reproduction_of_microorganisms.R>.
#' @inheritSection AMR Read more on our website!
#' The syntax used to transform the original data to a cleansed \R format, can be found here: <https://github.com/msberends/AMR/blob/master/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
@@ -53,26 +73,26 @@
#' mo_shortname("Chlamydophila psittaci")
#' # Note: 'Chlamydophila psittaci' (Everett et al., 1999) was renamed back to
#' # 'Chlamydia psittaci' (Page, 1968)
#' # [1] "C. psittaci"
#' #> [1] "C. psittaci"
#'
#' # Get any property from the entire taxonomic tree for all included species
#' mo_class("E. coli")
#' # [1] "Gammaproteobacteria"
#' #> [1] "Gammaproteobacteria"
#'
#' mo_family("E. coli")
#' # [1] "Enterobacteriaceae"
#' #> [1] "Enterobacteriaceae"
#'
#' mo_gramstain("E. coli") # based on kingdom and phylum, see ?mo_gramstain
#' # [1] "Gram negative"
#' #> [1] "Gram-negative"
#'
#' mo_ref("E. coli")
#' # [1] "Castellani et al., 1919"
#' #> [1] "Castellani et al., 1919"
#'
#' # Do not get mistaken - this package is about microorganisms
#' mo_kingdom("C. elegans")
#' # [1] "Fungi" # Fungi?!
#' #> [1] "Fungi" # Fungi?!
#' mo_name("C. elegans")
#' # [1] "Cladosporium elegans" # Because a microorganism was found
#' #> [1] "Cladosporium elegans" # Because a microorganism was found
NULL
#' Version info of included Catalogue of Life
@@ -80,9 +100,9 @@ NULL
#' This function returns information about the included data from the Catalogue of Life.
#' @seealso [microorganisms]
#' @details For DSMZ, see [microorganisms].
#' @return a [`list`], which prints in pretty format
#' @return a [list], which prints in pretty format
#' @inheritSection catalogue_of_life Catalogue of Life
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @export
catalogue_of_life_version <- function() {
@@ -92,19 +112,19 @@ catalogue_of_life_version <- function() {
lst <- list(catalogue_of_life =
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(filter(microorganisms, source == "CoL"))),
n = nrow(pm_filter(microorganisms, source == "CoL"))),
deutsche_sammlung_von_mikroorganismen_und_zellkulturen =
list(version = "Prokaryotic Nomenclature Up-to-Date from DSMZ",
url = catalogue_of_life$url_DSMZ,
yearmonth = catalogue_of_life$yearmonth_DSMZ,
n = nrow(filter(microorganisms, source == "DSMZ"))),
n = nrow(pm_filter(microorganisms, source == "DSMZ"))),
total_included =
list(
n_total_species = nrow(microorganisms),
n_total_synonyms = nrow(microorganisms.old)))
structure(.Data = lst,
class = c("catalogue_of_life_version", "list"))
set_clean_class(lst,
new_class = c("catalogue_of_life_version", "list"))
}
#' @method print catalogue_of_life_version

View File

@@ -1,30 +1,34 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Count available isolates
#' Count Available Isolates
#'
#' @description These functions can be used to count resistant/susceptible microbial isolates. All functions support quasiquotation with pipes, can be used in `summarise()` from the `dplyr` package and also support grouped variables, please see *Examples*.
#' @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
#' @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
@@ -35,13 +39,13 @@
#' The function [n_rsi()] is an alias of [count_all()]. They can be used to count all available isolates, i.e. where all input antibiotics have an available result (S, I or R). Their use is equal to `n_distinct()`. Their function is equal to `count_susceptible(...) + count_resistant(...)`.
#'
#' The function [count_df()] takes any variable from `data` that has an [`rsi`] class (created with [as.rsi()]) and counts the number of S's, I's and R's. It also supports grouped variables. The function [rsi_df()] works exactly like [count_df()], but adds the percentage of S, I and R.
#' @inheritSection proportion Combination therapy
#' @inheritSection proportion Combination Therapy
#' @seealso [`proportion_*`][proportion] to calculate microbial resistance and susceptibility.
#' @return An [`integer`]
#' @return An [integer]
#' @rdname count
#' @name count
#' @export
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # example_isolates is a data set available in the AMR package.
#' ?example_isolates
@@ -130,7 +134,10 @@ count_R <- function(..., only_all_tested = FALSE) {
#' @rdname count
#' @export
count_IR <- function(..., only_all_tested = FALSE) {
warning("Using 'count_IR' is discouraged; use 'count_resistant()' instead to not consider \"I\" being resistant.", call. = FALSE)
if (message_not_thrown_before("count_IR")) {
warning_("Using count_IR() is discouraged; use count_resistant() instead to not consider \"I\" being resistant.", call = FALSE)
remember_thrown_message("count_IR")
}
rsi_calc(...,
ab_result = c("I", "R"),
only_all_tested = only_all_tested,
@@ -158,7 +165,10 @@ count_SI <- function(..., only_all_tested = FALSE) {
#' @rdname count
#' @export
count_S <- function(..., only_all_tested = FALSE) {
warning("Using 'count_S' is discouraged; use 'count_susceptible()' instead to also consider \"I\" being susceptible.", call. = FALSE)
if (message_not_thrown_before("count_S")) {
warning_("Using count_S() is discouraged; use count_susceptible() instead to also consider \"I\" being susceptible.", call = FALSE)
remember_thrown_message("count_S")
}
rsi_calc(...,
ab_result = "S",
only_all_tested = only_all_tested,
@@ -185,7 +195,6 @@ count_df <- function(data,
language = get_locale(),
combine_SI = TRUE,
combine_IR = FALSE) {
rsi_calc_df(type = "count",
data = data,
translate_ab = translate_ab,

166
R/data.R
View File

@@ -1,30 +1,34 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Data sets with `r format(nrow(antibiotics) + nrow(antivirals), big.mark = ",")` antimicrobials
#' Data Sets with `r format(nrow(antibiotics) + nrow(antivirals), big.mark = ",")` Antimicrobials
#'
#' Two data sets containing all antibiotics/antimycotics and antivirals. Use [as.ab()] or one of the [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.
#' 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.
#' @format
#' ### For the [antibiotics] data set: a [`data.frame`] with `r nrow(antibiotics)` observations and `r ncol(antibiotics)` variables:
#' - `ab`\cr Antibiotic ID as used in this package (like `AMC`), using the official EARS-Net (European Antimicrobial Resistance Surveillance Network) codes where available
#' ## For the [antibiotics] data set: a [data.frame] 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
#' - `atc`\cr ATC code (Anatomical Therapeutic Chemical) as defined by the WHOCC, like `J01CR02`
#' - `cid`\cr Compound ID as found in PubChem
#' - `name`\cr Official name as used by WHONET/EARS-Net or the WHO
@@ -39,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 [data.frame] with `r nrow(antivirals)` observations and `r ncol(antivirals)` variables:
#' - `atc`\cr ATC code (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
@@ -53,13 +57,13 @@
#'
#' Synonyms (i.e. trade names) are 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:
#' ## 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/master/data-raw/antibiotics.txt>
#' * <https://github.com/msberends/AMR/raw/master/data-raw/antivirals.txt>
#'
#' Files in R format (with preserved data structure) can be found here:
#' Files in \R format (with preserved data structure) can be found here:
#'
#' * <https://github.com/msberends/AMR/raw/master/data/antibiotics.rda>
#' * <https://github.com/msberends/AMR/raw/master/data/antivirals.rda>
@@ -68,29 +72,37 @@
#' WHONET 2019 software: <http://www.whonet.org/software.html>
#'
#' European Commission Public Health PHARMACEUTICALS - COMMUNITY REGISTER: <http://ec.europa.eu/health/documents/community-register/html/atc.htm>
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection WHOCC WHOCC
#' @inheritSection AMR Read more on our website!
#' @seealso [microorganisms]
#' @inheritSection AMR Read more on Our Website!
#' @seealso [microorganisms], [intrinsic_resistant]
"antibiotics"
#' @rdname antibiotics
"antivirals"
#' Data set with `r format(nrow(microorganisms), big.mark = ",")` microorganisms
#' Data Set with `r format(nrow(microorganisms), big.mark = ",")` Microorganisms
#'
#' A data set containing the microbial taxonomy of six kingdoms from the Catalogue of Life. 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 [data.frame] 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
#' - `rank`\cr Text of the taxonomic rank of the microorganism, like `"species"` or `"genus"`
#' - `ref`\cr Author(s) and year of concerning scientific publication
#' - `species_id`\cr ID of the species as used by the Catalogue of Life
#' - `source`\cr Either "CoL", "DSMZ" (see Source) or "manually added"
#' - `source`\cr Either "CoL", "DSMZ" (see *Source*) or "manually added"
#' - `prevalence`\cr Prevalence of the microorganism, see [as.mo()]
#' - `snomed`\cr SNOMED code of the microorganism. Use [mo_snomed()] to retrieve it quickly, see [mo_property()].
#' @details Manually added were:
#' @details
#' Please note that entries are only based on the Catalogue of Life and the LPSN (see below). Since these sources incorporate entries based on (recent) publications in the International Journal of Systematic and Evolutionary Microbiology (IJSEM), it can happen that the year of publication is sometimes later than one might expect.
#'
#' For example, *Staphylococcus pettenkoferi* was newly named in Diagnostic Microbiology and Infectious Disease in 2002 (PMID 12106949), but it was not before 2007 that a publication in IJSEM followed (PMID 17625191). Consequently, the AMR package returns 2007 for `mo_year("S. pettenkoferi")`.
#'
#' ## Manually additions
#' For convenience, some entries were added manually:
#'
#' - 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* (*Trichomonas vaginalis*, and its family and genus)
@@ -98,28 +110,29 @@
#' - 1 entry of *Blastocystis* (*Blastocystis hominis*), although it officially does not exist (Noel *et al.* 2005, PMID 15634993)
#' - 5 other 'undefined' entries (unknown, unknown Gram negatives, unknown Gram positives, unknown yeast and unknown fungus)
#' - 6 families under the Enterobacterales order, according to Adeolu *et al.* (2016, PMID 27620848), that are not (yet) in the Catalogue of Life
#' - `r format(nrow(filter(microorganisms, source == "DSMZ")), big.mark = ",")` species from the DSMZ (Deutsche Sammlung von Mikroorganismen und Zellkulturen) since the DSMZ contain the latest taxonomic information based on recent publications
#' - `r format(nrow(subset(microorganisms, source == "DSMZ")), big.mark = ",")` species from the DSMZ (Deutsche Sammlung von Mikroorganismen und Zellkulturen) since the DSMZ contain the latest taxonomic information based on recent publications
#'
#' ### Direct download
#' This data set is available as 'flat file' for use even without R - you can find the file here:
#' ## 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/master/data-raw/microorganisms.txt>
#'
#' The file in R format (with preserved data structure) can be found here:
#' The file in \R format (with preserved data structure) can be found here:
#'
#' * <https://github.com/msberends/AMR/raw/master/data/microorganisms.rda>
#' @section About the records from DSMZ (see source):
#' @section About the Records from DSMZ (see *Source*):
#' Names of prokaryotes are defined as being validly published by the International Code of Nomenclature of Bacteria. Validly published are all names which are included in the Approved Lists of Bacterial Names and the names subsequently published in the International Journal of Systematic Bacteriology (IJSB) and, from January 2000, in the International Journal of Systematic and Evolutionary Microbiology (IJSEM) as original articles or in the validation lists.
#' *(from <https://www.dsmz.de/services/online-tools/prokaryotic-nomenclature-up-to-date/complete-list-readme>)*
#' *(from <https://www.dsmz.de/services/online-tools/prokaryotic-nomenclature-up-to-date>)*
#'
#' In February 2020, the DSMZ records were merged with the List of Prokaryotic names with Standing in Nomenclature (LPSN).
#' @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
#' 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}
#'
#' Leibniz Institute DSMZ-German Collection of Microorganisms and Cell Cultures, Germany, Prokaryotic Nomenclature Up-to-Date, <https://www.dsmz.de/services/online-tools/prokaryotic-nomenclature-up-to-date> and <https://lpsn.dsmz.de> (check included version with [catalogue_of_life_version()]).
#' @inheritSection AMR Read more on our website!
#' @seealso [as.mo()], [mo_property()], [microorganisms.codes]
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @seealso [as.mo()], [mo_property()], [microorganisms.codes], [intrinsic_resistant]
"microorganisms"
catalogue_of_life <- list(
@@ -130,37 +143,39 @@ catalogue_of_life <- list(
yearmonth_DSMZ = "May 2020"
)
#' Data set with previously accepted taxonomic names
#' 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 [data.frame] 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()]
#' @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 Read more on our website!
#' 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]
"microorganisms.old"
#' Translation table with `r format(nrow(microorganisms.codes), big.mark = ",")` common microorganism codes
#' 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 [data.frame] 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
#' @inheritSection catalogue_of_life Catalogue of Life
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @seealso [as.mo()] [microorganisms]
"microorganisms.codes"
#' Data set with `r format(nrow(example_isolates), big.mark = ",")` example isolates
#' 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 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:
#' @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
@@ -170,35 +185,37 @@ catalogue_of_life <- list(
#' - `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(sapply(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 Read more on our website!
#' - `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!
"example_isolates"
#' Data set with unclean data
#' 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 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 [data.frame] 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 Read more on our website!
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
"example_isolates_unclean"
#' Data set with `r format(nrow(WHONET), big.mark = ",")` isolates - WHONET example
#' 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 data itself was based on our [example_isolates] data set.
#' @format A [`data.frame`] with `r format(nrow(WHONET), big.mark = ",")` observations and `r ncol(WHONET)` variables:
#' 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:
#' - `Identification number`\cr ID of the sample
#' - `Specimen number`\cr ID of the specimen
#' - `Organism`\cr Name of the microorganism. Before analysis, you should transform this to a valid microbial class, using [as.mo()].
#' - `Country`\cr Country of origin
#' - `Laboratory`\cr Name of laboratory
#' - `Last name`\cr Last name of patient
#' - `First name`\cr Initial of patient
#' - `Sex`\cr Gender of patient
#' - `Age`\cr Age of patient
#' - `Last name`\cr Fictitious last name of patient
#' - `First name`\cr Fictitious initial of patient
#' - `Sex`\cr Fictitious gender of patient
#' - `Age`\cr Fictitious age of patient
#' - `Age category`\cr Age group, can also be looked up using [age_groups()]
#' - `Date of admission`\cr Date of hospital admission
#' - `Specimen date`\cr Date when specimen was received at laboratory
@@ -215,14 +232,15 @@ catalogue_of_life <- list(
#' - `Inducible clindamycin resistance`\cr Clindamycin can be induced?
#' - `Comment`\cr Other comments
#' - `Date of data entry`\cr Date this data was entered in WHONET
#' - `AMP_ND10:CIP_EE`\cr `r sum(sapply(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 Read more on our website!
#' - `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!
"WHONET"
#' Data set for R/SI interpretation
#' Data Set for R/SI Interpretation
#'
#' Data set to interpret MIC and disk diffusion to R/SI values. Included guidelines are CLSI (2011-2019) and EUCAST (2011-2020). 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:
#' Data set to interpret MIC and disk diffusion to R/SI values. Included guidelines are 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)))`) and 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)))`). 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:
#' - `guideline`\cr Name of the guideline
#' - `method`\cr Either "MIC" or "DISK"
#' - `site`\cr Body site, e.g. "Oral" or "Respiratory"
@@ -234,5 +252,45 @@ catalogue_of_life <- list(
#' - `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/master/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.
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @seealso [intrinsic_resistant]
"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:
#' - `microorganism`\cr Name of the microorganism
#' - `antibiotic`\cr Name of the antibiotic drug
#' @details The repository of this `AMR` package contains a file comprising this exact data set: <https://github.com/msberends/AMR/blob/master/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.
#'
#' This data set is based on `r format_eucast_version_nr(3.2)`.
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' if (require("dplyr")) {
#' intrinsic_resistant %>%
#' filter(antibiotic == "Vancomycin", microorganism %like% "Enterococcus") %>%
#' pull(microorganism)
#' # [1] "Enterococcus casseliflavus" "Enterococcus gallinarum"
#' }
"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:
#' - `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)`
#' - `dose`\cr Dose, such as "2 g" or "25 mg/kg"
#' - `dose_times`\cr Number of times a dose must be administered
#' - `administration`\cr Route of administration, either `r vector_or(dosage$administration)`
#' - `notes`\cr Additional dosage notes
#' - `original_txt`\cr Original text in the PDF file of EUCAST
#' - `eucast_version`\cr Version number of the EUCAST Clinical Breakpoints guideline to which these dosages apply
#' @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!
"dosage"

View File

@@ -1,69 +1,47 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Deprecated functions
#' 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!
#' @export
#' @inheritSection lifecycle Retired Lifecycle
#' @inheritSection AMR Read more on Our Website!
#' @keywords internal
#' @name AMR-deprecated
#' @export
portion_R <- function(...) {
.Deprecated("resistance()", package = "AMR")
proportion_R(...)
}
#' @rdname AMR-deprecated
#' @export
portion_IR <- function(...) {
.Deprecated("proportion_IR()", package = "AMR")
proportion_IR(...)
}
#' @rdname AMR-deprecated
#' @export
portion_I <- function(...) {
.Deprecated("proportion_I()", package = "AMR")
proportion_I(...)
}
#' @rdname AMR-deprecated
#' @export
portion_SI <- function(...) {
.Deprecated("susceptibility()", package = "AMR")
proportion_SI(...)
}
#' @rdname AMR-deprecated
#' @export
portion_S <- function(...) {
.Deprecated("proportion_S()", package = "AMR")
proportion_S(...)
}
#' @rdname AMR-deprecated
#' @export
portion_df <- function(...) {
.Deprecated("proportion_df()", package = "AMR")
proportion_df(...)
p_symbol <- function(p, emptychar = " ") {
.Deprecated(package = "AMR", new = "cleaner::p_symbol")
p <- as.double(p)
s <- rep(NA_character_, length(p))
s[p <= 1] <- emptychar
s[p <= 0.100] <- "."
s[p <= 0.050] <- "*"
s[p <= 0.010] <- "**"
s[p <= 0.001] <- "***"
s
}

139
R/disk.R
View File

@@ -1,48 +1,52 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Class 'disk'
#' Transform Input to Disk Diffusion Diameters
#'
#' This transforms a vector to a new class [`disk`], which is a growth zone size (around an antibiotic disk) in millimetres between 6 and 50.
#' @inheritSection lifecycle Stable lifecycle
#' 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
#' @details Interpret disk values as RSI values with [as.rsi()]. It supports guidelines from EUCAST and CLSI.
#' @return An [`integer`] with additional new class [`disk`]
#' @return An [integer] with additional class [`disk`]
#' @aliases disk
#' @export
#' @seealso [as.rsi()]
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' \dontrun{
#' \donttest{
#' # transform existing disk zones to the `disk` class
#' library(dplyr)
#' df <- data.frame(microorganism = "E. coli",
#' AMP = 20,
#' CIP = 14,
#' GEN = 18,
#' TOB = 16)
#' df <- df %>% mutate_at(vars(AMP:TOB), as.disk)
#' df
#' df[, 2:5] <- lapply(df[, 2:5], as.disk)
#' # same with dplyr:
#' # df %>% mutate(across(AMP:TOB, as.disk))
#'
#' # interpret disk values, see ?as.rsi
#' as.rsi(x = as.disk(18),
@@ -53,8 +57,11 @@
#' as.rsi(df)
#' }
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)
if (!is.disk(x)) {
x <- x %>% unlist()
x <- x %pm>% unlist()
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
@@ -62,31 +69,54 @@ as.disk <- function(x, na.rm = FALSE) {
na_before <- length(x[is.na(x)])
# force it to be integer
x <- suppressWarnings(as.integer(x))
# heavily based on cleaner::clean_double():
clean_double2 <- function(x, remove = "[^0-9.,-]", fixed = FALSE) {
x <- gsub(",", ".", x)
# remove ending dot/comma
x <- gsub("[,.]$", "", x)
# only keep last dot/comma
reverse <- function(x) vapply(FUN.VALUE = character(1), lapply(strsplit(x, NULL), rev), paste, collapse = "")
x <- sub("{{dot}}", ".",
gsub(".", "",
reverse(sub(".", "}}tod{{",
reverse(x),
fixed = TRUE)),
fixed = TRUE),
fixed = TRUE)
x_clean <- gsub(remove, "", x, ignore.case = TRUE, fixed = fixed)
# remove everything that is not a number or dot
as.numeric(gsub("[^0-9.]+", "", x_clean))
}
# round up and make it an integer
x <- as.integer(ceiling(clean_double2(x)))
# disks can never be less than 6 mm (size of smallest disk) or more than 50 mm
x[x < 6 | x > 50] <- NA_integer_
na_after <- length(x[is.na(x)])
if (na_before != na_after) {
list_missing <- x.bak[is.na(x) & !is.na(x.bak)] %>%
unique() %>%
list_missing <- x.bak[is.na(x) & !is.na(x.bak)] %pm>%
unique() %pm>%
sort()
list_missing <- paste0('"', list_missing, '"', collapse = ", ")
warning(na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid disk zones: ",
list_missing, call. = FALSE)
warning_(na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid disk zones: ",
list_missing, call = FALSE)
}
}
structure(as.integer(x),
class = c("disk", "integer"))
set_clean_class(as.integer(x),
new_class = c("disk", "integer"))
}
all_valid_disks <- function(x) {
x_disk <- suppressWarnings(as.disk(x[!is.na(x)]))
!any(is.na(x_disk)) & !all(is.na(x))
if (!inherits(x, c("disk", "character", "numeric", "integer"))) {
return(FALSE)
}
x_disk <- tryCatch(suppressWarnings(as.disk(x[!is.na(x)])),
error = function(e) NA)
!any(is.na(x_disk)) && !all(is.na(x))
}
#' @rdname as.disk
@@ -95,6 +125,18 @@ is.disk <- function(x) {
inherits(x, "disk")
}
# will be exported using s3_register() in R/zzz.R
pillar_shaft.disk <- function(x, ...) {
out <- trimws(format(x))
out[is.na(x)] <- font_na(NA)
create_pillar_column(out, align = "right", width = 2)
}
# will be exported using s3_register() in R/zzz.R
type_sum.disk <- function(x, ...) {
"disk"
}
#' @method print disk
#' @export
#' @noRd
@@ -103,6 +145,30 @@ print.disk <- function(x, ...) {
print(as.integer(x), quote = FALSE)
}
#' @method plot disk
#' @export
#' @importFrom graphics barplot axis
#' @rdname plot
plot.disk <- function(x,
main = paste("Disk zones values of", deparse(substitute(x))),
ylab = "Frequency",
xlab = "Disk diffusion (mm)",
axes = FALSE,
...) {
meet_criteria(main, allow_class = "character", has_length = 1)
meet_criteria(ylab, allow_class = "character", has_length = 1)
meet_criteria(xlab, allow_class = "character", has_length = 1)
meet_criteria(axes, allow_class = "logical", has_length = 1)
barplot(table(x),
ylab = ylab,
xlab = xlab,
axes = axes,
main = main,
...)
axis(2, seq(0, max(table(x))))
}
#' @method [ disk
#' @export
#' @noRd
@@ -146,3 +212,24 @@ c.disk <- function(x, ...) {
attributes(y) <- attributes(x)
y
}
#' @method unique disk
#' @export
#' @noRd
unique.disk <- function(x, incomparables = FALSE, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
# will be exported using s3_register() in R/zzz.R
get_skimmers.disk <- function(column) {
skimr::sfl(
skim_type = "disk",
min = ~min(as.double(.), na.rm = TRUE),
max = ~max(as.double(.), na.rm = TRUE),
median = ~stats::median(as.double(.), na.rm = TRUE),
n_unique = ~pm_n_distinct(., na.rm = TRUE),
hist = ~skimr::inline_hist(stats::na.omit(as.double(.)))
)
}

182
R/episode.R Normal file
View File

@@ -0,0 +1,182 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' 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`)
#' @param episode_days length of the required episode in days, see *Details*
#' @param ... arguments passed on to [as.Date()]
#' @details
#' Dates are first sorted from old to new. The oldest date will mark the start of the first episode. After this date, the next date will be marked that is at least `episode_days` days later than the start of the first episode. From that second marked date on, the next date will be marked that is at least `episode_days` days later than the start of the second episode which will be the start of the third episode, and so on. Before the vector is being returned, the original order will be restored.
#'
#' The [first_isolate()] function is a wrapper around the [is_new_episode()] function, but is more efficient for data sets containing microorganism codes or names.
#'
#' The `dplyr` package is not required for these functions to work, but these functions support [variable grouping][dplyr::group_by()] and work conveniently inside `dplyr` verbs such as [`filter()`][dplyr::filter()], [`mutate()`][dplyr::mutate()] and [`summarise()`][dplyr::summarise()].
#' @return
#' * [get_episode()]: a [double] vector
#' * [is_new_episode()]: a [logical] vector
#' @seealso [first_isolate()]
#' @rdname get_episode
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a dataset available in the AMR package.
#' # See ?example_isolates.
#'
#' get_episode(example_isolates$date, episode_days = 60)
#' is_new_episode(example_isolates$date, episode_days = 60)
#'
#' # filter on results from the third 60-day episode only, using base R
#' example_isolates[which(get_episode(example_isolates$date, 60) == 3), ]
#'
#' \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)) %>%
#' group_by(condition) %>%
#' mutate(new_episode = is_new_episode(date, 365))
#'
#' example_isolates %>%
#' group_by(hospital_id, patient_id) %>%
#' transmute(date,
#' patient_id,
#' 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),
#' n_episodes_365 = sum(is_new_episode(date, episode_days = 365)),
#' n_episodes_60 = sum(is_new_episode(date, episode_days = 60)),
#' n_episodes_30 = sum(is_new_episode(date, episode_days = 30)))
#'
#'
#' # grouping on patients and microorganisms leads to the same results
#' # as first_isolate():
#' x <- example_isolates %>%
#' filter(first_isolate(., include_unknown = TRUE))
#'
#' y <- example_isolates %>%
#' group_by(patient_id, mo) %>%
#' filter(is_new_episode(date, 365))
#'
#' identical(x$patient_id, y$patient_id)
#'
#' # 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))
#' }
#' }
get_episode <- function(x, episode_days, ...) {
meet_criteria(x, allow_class = c("Date", "POSIXt"))
meet_criteria(episode_days, allow_class = c("numeric", "double", "integer"), has_length = 1)
exec_episode(type = "sequential",
x = x,
episode_days = episode_days,
... = ...)
}
#' @rdname get_episode
#' @export
is_new_episode <- function(x, episode_days, ...) {
meet_criteria(x, allow_class = c("Date", "POSIXt"))
meet_criteria(episode_days, allow_class = c("numeric", "double", "integer"), has_length = 1)
exec_episode(type = "logical",
x = x,
episode_days = episode_days,
... = ...)
}
exec_episode <- function(type, x, episode_days, ...) {
x <- as.double(as.Date(x, ...)) # as.Date() for POSIX classes
if (length(x) == 1) {
if (type == "logical") {
return(TRUE)
} else if (type == "sequential") {
return(1)
}
} else if (length(x) == 2) {
if (max(x) - min(x) >= episode_days) {
if (type == "logical") {
return(c(TRUE, TRUE))
} else if (type == "sequential") {
return(c(1, 2))
}
} else {
if (type == "logical") {
return(c(TRUE, FALSE))
} else if (type == "sequential") {
return(c(1, 1))
}
}
}
# I asked on StackOverflow:
# https://stackoverflow.com/questions/42122245/filter-one-row-every-year
exec <- function(x, episode_days) {
indices <- integer()
start <- x[1]
ind <- 1
indices[1] <- 1
for (i in 2:length(x)) {
if (isTRUE((x[i] - start) >= episode_days)) {
ind <- ind + 1
if (type == "logical") {
indices[ind] <- i
}
start <- x[i]
}
if (type == "sequential") {
indices[i] <- ind
}
}
if (type == "logical") {
result <- rep(FALSE, length(x))
result[indices] <- TRUE
result
} else if (type == "sequential") {
indices
}
}
df <- data.frame(x = x,
y = seq_len(length(x))) %pm>%
pm_arrange(x)
df$new <- exec(df$x, episode_days)
df %pm>%
pm_arrange(y) %pm>%
pm_pull(new)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +1,32 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Filter isolates on result in antimicrobial class
#' Filter Isolates on Result in Antimicrobial Class
#'
#' Filter isolates on results in specific antimicrobial classes. This makes it easy to filter on isolates that were tested for e.g. any aminoglycoside, or to filter on carbapenem-resistant isolates without the need to specify the drugs.
#' @inheritSection lifecycle Stable lifecycle
#' @inheritSection lifecycle Stable Lifecycle
#' @param x a data set
#' @param ab_class an antimicrobial class, like `"carbapenems"`. The columns `group`, `atc_group1` and `atc_group2` of the [antibiotics] data set will be searched (case-insensitive) for this value.
#' @param result an antibiotic result: S, I or R (or a combination of more of them)
@@ -33,56 +37,67 @@
#' @seealso [antibiotic_class_selectors()] for the `select()` equivalent.
#' @export
#' @examples
#' \dontrun{
#' library(dplyr)
#'
#' # filter on isolates that have any result for any aminoglycoside
#' example_isolates %>% filter_ab_class("aminoglycoside")
#' example_isolates %>% filter_aminoglycosides()
#'
#' # this is essentially the same as (but without determination of column names):
#' example_isolates %>%
#' filter_at(.vars = vars(c("GEN", "TOB", "AMK", "KAN")),
#' .vars_predicate = any_vars(. %in% c("S", "I", "R")))
#'
#'
#' # filter on isolates that show resistance to ANY aminoglycoside
#' example_isolates %>% filter_aminoglycosides("R", "any")
#'
#' # filter on isolates that show resistance to ALL aminoglycosides
#' example_isolates %>% filter_aminoglycosides("R", "all")
#'
#' # filter on isolates that show resistance to
#' # any aminoglycoside and any fluoroquinolone
#' example_isolates %>%
#' filter_aminoglycosides("R") %>%
#' filter_fluoroquinolones("R")
#'
#' # filter on isolates that show resistance to
#' # all aminoglycosides and all fluoroquinolones
#' example_isolates %>%
#' filter_aminoglycosides("R", "all") %>%
#' filter_fluoroquinolones("R", "all")
#' filter_aminoglycosides(example_isolates)
#'
#' # with dplyr 1.0.0 and higher (that adds 'across()'), this is equal:
#' example_isolates %>% filter_carbapenems("R", "all")
#' example_isolates %>% filter(across(carbapenems(), ~. == "R"))
#' \donttest{
#' if (require("dplyr")) {
#'
#' # filter on isolates that have any result for any aminoglycoside
#' example_isolates %>% filter_aminoglycosides()
#' example_isolates %>% filter_ab_class("aminoglycoside")
#'
#' # this is essentially the same as (but without determination of column names):
#' example_isolates %>%
#' filter_at(.vars = vars(c("GEN", "TOB", "AMK", "KAN")),
#' .vars_predicate = any_vars(. %in% c("S", "I", "R")))
#'
#'
#' # filter on isolates that show resistance to ANY aminoglycoside
#' example_isolates %>% filter_aminoglycosides("R", "any")
#'
#' # filter on isolates that show resistance to ALL aminoglycosides
#' example_isolates %>% filter_aminoglycosides("R", "all")
#'
#' # filter on isolates that show resistance to
#' # any aminoglycoside and any fluoroquinolone
#' example_isolates %>%
#' filter_aminoglycosides("R") %>%
#' filter_fluoroquinolones("R")
#'
#' # filter on isolates that show resistance to
#' # all aminoglycosides and all fluoroquinolones
#' example_isolates %>%
#' filter_aminoglycosides("R", "all") %>%
#' filter_fluoroquinolones("R", "all")
#'
#' # with dplyr 1.0.0 and higher (that adds 'across()'), this is all equal:
#' # (though the row names on the first are more correct)
#' example_isolates %>% filter_carbapenems("R", "all")
#' example_isolates %>% filter(across(carbapenems(), ~. == "R"))
#' example_isolates %>% filter(across(carbapenems(), function(x) x == "R"))
#' }
#' }
filter_ab_class <- function(x,
ab_class,
result = NULL,
scope = "any",
...) {
.call_depth <- list(...)$`.call_depth`
if (is.null(.call_depth)) {
.call_depth <- 0
}
meet_criteria(x, allow_class = "data.frame", .call_depth = .call_depth)
meet_criteria(ab_class, allow_class = "character", has_length = 1, .call_depth = .call_depth)
meet_criteria(result, allow_class = "character", has_length = c(1, 2, 3), allow_NULL = TRUE, .call_depth = .call_depth)
meet_criteria(scope, allow_class = "character", has_length = 1, is_in = c("all", "any"), .call_depth = .call_depth)
check_dataset_integrity()
stop_ifnot(is.data.frame(x), "`x` must be a data frame")
# save to return later
x_class <- class(x)
x.bak <- x
x <- as.data.frame(x, stringsAsFactors = FALSE)
scope <- scope[1L]
if (is.null(result)) {
result <- c("S", "I", "R")
}
@@ -93,9 +108,9 @@ filter_ab_class <- function(x,
stop_ifnot(all(scope %in% c("any", "all")), "`scope` must be one of: 'any', 'all'")
# get all columns in data with names that resemble antibiotics
ab_in_data <- suppressMessages(get_column_abx(x))
ab_in_data <- get_column_abx(x, info = FALSE)
if (length(ab_in_data) == 0) {
message(font_blue("NOTE: no columns with class <rsi> found (see ?as.rsi), data left unchanged."))
message_("No columns with class <rsi> found (see ?as.rsi), data left unchanged.")
return(x.bak)
}
# get reference data
@@ -109,15 +124,15 @@ filter_ab_class <- function(x,
atc_group2 %like% ab_class)
ab_group <- find_ab_group(ab_class)
if (ab_group == "") {
message(font_blue(paste0("NOTE: unknown antimicrobial class '", ab_class.bak, "', data left unchanged.")))
message_("Unknown antimicrobial class '", ab_class.bak, "', data left unchanged.")
return(x.bak)
}
# get the columns with a group names in the chosen ab class
agents <- ab_in_data[names(ab_in_data) %in% ab_reference$ab]
if (length(agents) == 0) {
message(font_blue(paste0("NOTE: no antimicrobial agents of class ", ab_group,
" found (such as ", find_ab_names(ab_class, 2),
"), data left unchanged.")))
message_("no antimicrobial agents of class ", ab_group,
" found (such as ", find_ab_names(ab_class, 2),
"), data left unchanged.")
return(x.bak)
}
@@ -145,13 +160,13 @@ filter_ab_class <- function(x,
# sort columns on official name
agents <- agents[order(ab_name(names(agents), language = NULL))]
message(font_blue(paste0("Filtering on ", ab_group, ": ", scope,
paste(paste0("`", font_bold(agents, collapse = NULL),
"` (", ab_name(names(agents), tolower = TRUE, language = NULL), ")"),
collapse = scope_txt),
operator, toString(result))))
x_transposed <- as.list(as.data.frame(t(x[, agents, drop = FALSE])))
filtered <- sapply(x_transposed, function(y) scope_fn(y %in% result, na.rm = TRUE))
message_("Filtering on ", ab_group, ": ", scope,
paste(paste0("`", font_bold(agents, collapse = NULL),
"` (", ab_name(names(agents), tolower = TRUE, language = NULL), ")"),
collapse = scope_txt),
operator, toString(result), as_note = FALSE)
x_transposed <- as.list(as.data.frame(t(x[, agents, drop = FALSE]), stringsAsFactors = FALSE))
filtered <- vapply(FUN.VALUE = logical(1), x_transposed, function(y) scope_fn(y %in% result, na.rm = TRUE))
x <- x[which(filtered), , drop = FALSE]
class(x) <- x_class
x
@@ -167,6 +182,7 @@ filter_aminoglycosides <- function(x,
ab_class = "aminoglycoside",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -180,6 +196,7 @@ filter_carbapenems <- function(x,
ab_class = "carbapenem",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -193,6 +210,7 @@ filter_cephalosporins <- function(x,
ab_class = "cephalosporin",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -206,6 +224,7 @@ filter_1st_cephalosporins <- function(x,
ab_class = "cephalosporins (1st gen.)",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -219,6 +238,7 @@ filter_2nd_cephalosporins <- function(x,
ab_class = "cephalosporins (2nd gen.)",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -232,6 +252,7 @@ filter_3rd_cephalosporins <- function(x,
ab_class = "cephalosporins (3rd gen.)",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -245,6 +266,7 @@ filter_4th_cephalosporins <- function(x,
ab_class = "cephalosporins (4th gen.)",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -258,6 +280,7 @@ filter_5th_cephalosporins <- function(x,
ab_class = "cephalosporins (5th gen.)",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -271,6 +294,7 @@ filter_fluoroquinolones <- function(x,
ab_class = "fluoroquinolone",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -284,6 +308,7 @@ filter_glycopeptides <- function(x,
ab_class = "glycopeptide",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -297,6 +322,7 @@ filter_macrolides <- function(x,
ab_class = "macrolide",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -310,6 +336,7 @@ filter_penicillins <- function(x,
ab_class = "penicillin",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -323,6 +350,7 @@ filter_tetracyclines <- function(x,
ab_class = "tetracycline",
result = result,
scope = scope,
.call_depth = 1,
...)
}
@@ -336,14 +364,14 @@ find_ab_group <- function(ab_class) {
"macrolide",
"tetracycline"),
paste0(ab_class, "s"),
antibiotics %>%
antibiotics %pm>%
subset(group %like% ab_class |
atc_group1 %like% ab_class |
atc_group2 %like% ab_class) %>%
pull(group) %>%
unique() %>%
tolower() %>%
sort() %>%
atc_group2 %like% ab_class) %pm>%
pm_pull(group) %pm>%
unique() %pm>%
tolower() %pm>%
sort() %pm>%
paste(collapse = "/")
)
}

View File

@@ -1,72 +1,90 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Determine first (weighted) isolates
#' Determine First (Weighted) Isolates
#'
#' Determine first (weighted) isolates of all microorganisms of every patient per episode and (if needed) per specimen type.
#' @inheritSection lifecycle Stable lifecycle
#' @param x a [`data.frame`] containing isolates.
#' @param col_date column name of the result date (or date that is was received on the lab), defaults to the first column of with a date class
#' Determine first (weighted) isolates of all microorganisms of every patient per episode and (if needed) per specimen type. 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.
#' @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 (like test codes for screening). In that case `testcodes_exclude` will be ignored.
#' @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_keyantibiotics column name of the key antibiotics to determine first *weighted* isolates, see [key_antibiotics()]. Defaults to the first column that starts with 'key' followed by 'ab' or 'antibiotics' (case insensitive). Use `col_keyantibiotics = FALSE` to prevent this.
#' @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 col_keyantibiotics column name of the key antibiotics to determine first (weighted) isolates, see [key_antibiotics()]. Defaults to the first column that starts with 'key' followed by 'ab' or 'antibiotics' (case insensitive). Use `col_keyantibiotics = FALSE` to prevent this.
#' @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 character vector with test codes that should be excluded (case-insensitive)
#' @param icu_exclude logical whether ICU isolates should be excluded (rows with value `TRUE` in column `col_icu`)
#' @param specimen_group value in column `col_specimen` to filter on
#' @param type type to determine weighed isolates; can be `"keyantibiotics"` or `"points"`, see Details
#' @param ignore_I logical to determine whether antibiotic interpretations with `"I"` will be ignored when `type = "keyantibiotics"`, see Details
#' @param points_threshold points until the comparison of key antibiotics will lead to inclusion of an isolate when `type = "points"`, see Details
#' @param icu_exclude logical whether ICU isolates should be excluded (rows with value `TRUE` in the column set with `col_icu`)
#' @param specimen_group value in the column set with `col_specimen` to filter on
#' @param type type to determine weighed isolates; can be `"keyantibiotics"` or `"points"`, see *Details*
#' @param ignore_I logical to determine whether antibiotic interpretations with `"I"` will be ignored when `type = "keyantibiotics"`, see *Details*
#' @param points_threshold points until the comparison of key antibiotics will lead to inclusion of an isolate when `type = "points"`, see *Details*
#' @param info print progress
#' @param include_unknown logical to determine whether 'unknown' microorganisms should be included too, i.e. microbial code `"UNKNOWN"`, which defaults to `FALSE`. For WHONET users, this means that all records with organism code `"con"` (*contamination*) will be excluded at default. Isolates with a microbial ID of `NA` will always be excluded as first isolate.
#' @param ... parameters passed on to the [first_isolate()] function
#' @details **WHY THIS IS SO IMPORTANT** \cr
#' To conduct an analysis of antimicrobial resistance, you should only include the first isolate of every patient per episode [(ref)](https://www.ncbi.nlm.nih.gov/pubmed/17304462). If you would not do this, you could easily get an overestimate or underestimate of the resistance of an antibiotic. Imagine that a patient was admitted with an MRSA and that it was found in 5 different blood cultures the following week. The resistance percentage of oxacillin of all *S. aureus* isolates would be overestimated, because you included this MRSA more than once. It would be [selection bias](https://en.wikipedia.org/wiki/Selection_bias).
#'
#' @param ... arguments passed on to [first_isolate()] when using [filter_first_isolate()], or arguments passed on to [key_antibiotics()] when using [filter_first_weighted_isolate()]
#' @details
#' These functions are context-aware when used inside `dplyr` verbs, such as `filter()`, `mutate()` and `summarise()`. This means that then the `x` argument can be left blank, see *Examples*.
#'
#' The [first_isolate()] function is a wrapper around the [is_new_episode()] function, but more efficient for data sets containing microorganism codes or names.
#'
#' All isolates with a microbial ID of `NA` will be excluded as first isolate.
#'
#' ## Why this is so Important
#' To conduct an analysis of antimicrobial resistance, you should only include the first isolate of every patient per episode [(Hindler *et al.* 2007)](https://pubmed.ncbi.nlm.nih.gov/17304462/). If you would not do this, you could easily get an overestimate or underestimate of the resistance of an antibiotic. Imagine that a patient was admitted with an MRSA and that it was found in 5 different blood cultures the following week. The resistance percentage of oxacillin of all *S. aureus* isolates would be overestimated, because you included this MRSA more than once. It would be [selection bias](https://en.wikipedia.org/wiki/Selection_bias).
#'
#' The functions [filter_first_isolate()] and [filter_first_weighted_isolate()] are helper functions to quickly filter on first isolates. The function [filter_first_isolate()] is essentially equal to one of:
#' ## `filter_*()` Shortcuts
#'
#' The functions [filter_first_isolate()] and [filter_first_weighted_isolate()] are helper functions to quickly filter on first isolates.
#'
#' The function [filter_first_isolate()] is essentially equal to either:
#'
#' ```
#' x %>% filter(first_isolate(., ...))
#' x[first_isolate(x, ...), ]
#'
#' x %>% filter(first_isolate(...))
#' ```
#'
#' The function [filter_first_weighted_isolate()] is essentially equal to:
#'
#' ```
#' x %>%
#' mutate(keyab = key_antibiotics(.)) %>%
#' mutate(only_weighted_firsts = first_isolate(x,
#' col_keyantibiotics = "keyab", ...)) %>%
#' filter(only_weighted_firsts == TRUE) %>%
#' select(-only_weighted_firsts, -keyab)
#' x %>%
#' mutate(keyab = key_antibiotics(.)) %>%
#' mutate(only_weighted_firsts = first_isolate(x,
#' col_keyantibiotics = "keyab", ...)) %>%
#' filter(only_weighted_firsts == TRUE) %>%
#' select(-only_weighted_firsts, -keyab)
#' ```
#' @section Key antibiotics:
#' There are two ways to determine whether isolates can be included as first *weighted* isolates which will give generally the same results:
#' @section Key Antibiotics:
#' There are two ways to determine whether isolates can be included as first weighted isolates which will give generally the same results:
#'
#' 1. Using `type = "keyantibiotics"` and parameter `ignore_I`
#' 1. Using `type = "keyantibiotics"` and argument `ignore_I`
#'
#' Any difference from S to R (or vice versa) will (re)select an isolate as a first weighted isolate. With `ignore_I = FALSE`, also differences from I to S|R (or vice versa) will lead to this. This is a reliable method and 30-35 times faster than method 2. Read more about this in the [key_antibiotics()] function.
#'
#' 2. Using `type = "points"` and parameter `points_threshold`
#' 2. Using `type = "points"` and argument `points_threshold`
#'
#' A difference from I to S|R (or vice versa) means 0.5 points, a difference from S to R (or vice versa) means 1 point. When the sum of points exceeds `points_threshold`, which default to `2`, an isolate will be (re)selected as a first weighted isolate.
#' @rdname first_isolate
@@ -76,54 +94,48 @@
#' @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/>.
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a dataset available in the AMR package.
#' # See ?example_isolates.
#'
#' \dontrun{
#' library(dplyr)
#' # Filter on first isolates:
#' example_isolates %>%
#' mutate(first_isolate = first_isolate(.)) %>%
#' filter(first_isolate == TRUE)
#'
#' # 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_weighted_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 3.7% higher than
#' # when you (erroneously) would have used all isolates for analysis.
#'
#'
#' ## OTHER EXAMPLES:
#' # basic filtering on first isolates
#' example_isolates[first_isolate(example_isolates), ]
#'
#' # Short-hand versions:
#' example_isolates %>%
#' filter_first_isolate()
#' # filtering based on isolates ----------------------------------------------
#' \donttest{
#' if (require("dplyr")) {
#' # filter on first isolates:
#' example_isolates %>%
#' mutate(first_isolate = first_isolate(.)) %>%
#' filter(first_isolate == TRUE)
#'
#' # short-hand versions:
#' example_isolates %>%
#' filter(first_isolate())
#' example_isolates %>%
#' filter_first_isolate()
#'
#' example_isolates %>%
#' filter_first_weighted_isolate()
#'
#' example_isolates %>%
#' filter_first_weighted_isolate()
#'
#'
#' # set key antibiotics to a new variable
#' x$keyab <- key_antibiotics(x)
#'
#' x$first_isolate <- first_isolate(x)
#'
#' x$first_isolate_weighed <- first_isolate(x, col_keyantibiotics = 'keyab')
#'
#' x$first_blood_isolate <- first_isolate(x, specimen_group = "Blood")
#' # 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_weighted_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 3.7% higher than
#' # when you (erroneously) would have used all isolates for analysis.
#' }
#' }
first_isolate <- function(x,
col_date = NULL,
@@ -143,11 +155,37 @@ first_isolate <- function(x,
info = interactive(),
include_unknown = FALSE,
...) {
if (missing(x)) {
x <- get_current_data(arg_name = "x", call = -2)
}
meet_criteria(x, allow_class = "data.frame") # also checks dimensions to be >0
meet_criteria(col_date, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_patient_id, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_testcode, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
if (isFALSE(col_specimen)) {
col_specimen <- NULL
}
meet_criteria(col_specimen, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_icu, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
if (isFALSE(col_keyantibiotics)) {
col_keyantibiotics <- NULL
}
meet_criteria(col_keyantibiotics, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(episode_days, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(testcodes_exclude, allow_class = "character", allow_NULL = TRUE)
meet_criteria(icu_exclude, allow_class = "logical", has_length = 1)
meet_criteria(specimen_group, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(type, allow_class = "character", has_length = 1)
meet_criteria(ignore_I, allow_class = "logical", has_length = 1)
meet_criteria(points_threshold, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(info, allow_class = "logical", has_length = 1)
meet_criteria(include_unknown, allow_class = "logical", has_length = 1)
dots <- unlist(list(...))
if (length(dots) != 0) {
# backwards compatibility with old parameters
dots.names <- dots %>% names()
# backwards compatibility with old arguments
dots.names <- dots %pm>% names()
if ("filter_specimen" %in% dots.names) {
specimen_group <- dots[which(dots.names == "filter_specimen")]
}
@@ -156,13 +194,10 @@ first_isolate <- function(x,
}
}
stop_ifnot(is.data.frame(x), "`x` must be a data.frame")
stop_if(any(dim(x) == 0), "`x` must contain rows and columns")
# remove data.table, grouping from tibbles, etc.
x <- as.data.frame(x, stringsAsFactors = FALSE)
# try to find columns based on type
# try to find columns based on type
# -- mo
if (is.null(col_mo)) {
col_mo <- search_type_in_df(x = x, type = "mo")
@@ -181,7 +216,7 @@ first_isolate <- function(x,
# WHONET support
x$patient_id <- paste(x$`First name`, x$`Last name`, x$Sex)
col_patient_id <- "patient_id"
message(font_blue(paste0("NOTE: Using combined columns `", font_bold("First name"), "`, `", font_bold("Last name"), "` and `", font_bold("Sex"), "` as input for `col_patient_id`")))
message_("Using combined columns '", font_bold("First name"), "', '", font_bold("Last name"), "' and '", font_bold("Sex"), "' as input for `col_patient_id`")
} else {
col_patient_id <- search_type_in_df(x = x, type = "patient_id")
}
@@ -192,23 +227,17 @@ first_isolate <- function(x,
if (is.null(col_keyantibiotics)) {
col_keyantibiotics <- search_type_in_df(x = x, type = "keyantibiotics")
}
if (isFALSE(col_keyantibiotics)) {
col_keyantibiotics <- NULL
}
# -- specimen
if (is.null(col_specimen) & !is.null(specimen_group)) {
col_specimen <- search_type_in_df(x = x, type = "specimen")
}
if (isFALSE(col_specimen)) {
col_specimen <- NULL
}
# check if columns exist
check_columns_existance <- function(column, tblname = x) {
if (!is.null(column)) {
stop_ifnot(column %in% colnames(tblname),
"Column `", column, "` not found.", call = FALSE)
"Column '", column, "' not found.", call = FALSE)
}
}
@@ -236,7 +265,9 @@ first_isolate <- function(x,
}
# remove testcodes
if (!is.null(testcodes_exclude) & info == TRUE) {
message(font_black(paste0("[Criterion] Exclude test codes: ", toString(paste0("'", testcodes_exclude, "'")))))
message_("[Criterion] Exclude test codes: ", toString(paste0("'", testcodes_exclude, "'")),
add_fn = font_black,
as_note = FALSE)
}
if (is.null(col_specimen)) {
@@ -247,7 +278,9 @@ first_isolate <- function(x,
if (!is.null(specimen_group)) {
check_columns_existance(col_specimen, x)
if (info == TRUE) {
message(font_black(paste0("[Criterion] Exclude other than specimen group '", specimen_group, "'")))
message_("[Criterion] Exclude other than specimen group '", specimen_group, "'",
add_fn = font_black,
as_note = FALSE)
}
}
if (!is.null(col_keyantibiotics)) {
@@ -268,26 +301,45 @@ first_isolate <- function(x,
row.end <- nrow(x)
} else {
# filtering on specimen and only analyse these rows to save time
x <- x[order(pull(x, col_specimen),
x <- x[order(pm_pull(x, col_specimen),
x$newvar_patient_id,
x$newvar_genus_species,
x$newvar_date), ]
rownames(x) <- NULL
suppressWarnings(
row.start <- which(x %>% pull(col_specimen) == specimen_group) %>% min(na.rm = TRUE)
row.start <- which(x %pm>% pm_pull(col_specimen) == specimen_group) %pm>% min(na.rm = TRUE)
)
suppressWarnings(
row.end <- which(x %>% pull(col_specimen) == specimen_group) %>% max(na.rm = TRUE)
row.end <- which(x %pm>% pm_pull(col_specimen) == specimen_group) %pm>% max(na.rm = TRUE)
)
}
# no isolates found
# speed up - return immediately if obvious
if (abs(row.start) == Inf | abs(row.end) == Inf) {
if (info == TRUE) {
message(paste("=> Found", font_bold("no isolates")))
message_("=> Found ", font_bold("no isolates"),
add_fn = font_black,
as_note = FALSE)
}
return(rep(FALSE, nrow(x)))
}
if (row.start == row.end) {
if (info == TRUE) {
message_("=> Found ", font_bold("1 isolate"), ", as the data only contained 1 row",
add_fn = font_black,
as_note = FALSE)
}
return(TRUE)
}
if (length(c(row.start:row.end)) == pm_n_distinct(x[c(row.start:row.end), col_mo, drop = TRUE])) {
if (info == TRUE) {
message_("=> Found ", font_bold(paste(length(c(row.start:row.end)), "isolates")),
", as all isolates were different microorganisms",
add_fn = font_black,
as_note = FALSE)
}
return(rep(TRUE, length(c(row.start:row.end))))
}
# did find some isolates - add new index numbers of rows
x$newvar_row_index_sorted <- seq_len(nrow(x))
@@ -295,31 +347,9 @@ first_isolate <- function(x,
scope.size <- nrow(x[which(x$newvar_row_index_sorted %in% c(row.start + 1:row.end) &
!is.na(x$newvar_mo)), , drop = FALSE])
identify_new_year <- function(x, episode_days) {
# I asked on StackOverflow:
# https://stackoverflow.com/questions/42122245/filter-one-row-every-year
if (length(x) == 1) {
return(TRUE)
}
indices <- integer(0)
start <- x[1]
ind <- 1
indices[ind] <- ind
for (i in 2:length(x)) {
if (isTRUE(as.numeric(x[i] - start) >= episode_days)) {
ind <- ind + 1
indices[ind] <- i
start <- x[i]
}
}
result <- rep(FALSE, length(x))
result[indices] <- TRUE
return(result)
}
# Analysis of first isolate ----
x$other_pat_or_mo <- ifelse(x$newvar_patient_id == lag(x$newvar_patient_id) &
x$newvar_genus_species == lag(x$newvar_genus_species),
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)
x$episode_group <- paste(x$newvar_patient_id, x$newvar_genus_species)
@@ -327,8 +357,8 @@ first_isolate <- function(x,
function(g,
df = x,
days = episode_days) {
identify_new_year(x = df[which(df$episode_group == g), "newvar_date", drop = TRUE],
episode_days = days)
is_new_episode(x = df[which(df$episode_group == g), ]$newvar_date,
episode_days = days)
}))
weighted.notice <- ""
@@ -336,39 +366,43 @@ first_isolate <- function(x,
weighted.notice <- "weighted "
if (info == TRUE) {
if (type == "keyantibiotics") {
message(font_black(paste0("[Criterion] Base inclusion on key antibiotics, ",
ifelse(ignore_I == FALSE, "not ", ""),
"ignoring I")))
message_("[Criterion] Base inclusion on key antibiotics, ",
ifelse(ignore_I == FALSE, "not ", ""),
"ignoring I",
add_fn = font_black,
as_note = FALSE)
}
if (type == "points") {
message(font_black(paste0("[Criterion] Base inclusion on key antibiotics, using points threshold of "
, points_threshold)))
message_("[Criterion] Base inclusion on key antibiotics, using points threshold of "
, points_threshold,
add_fn = font_black,
as_note = FALSE)
}
}
type_param <- type
x$other_key_ab <- !key_antibiotics_equal(y = x$newvar_key_ab,
z = lag(x$newvar_key_ab),
z = pm_lag(x$newvar_key_ab),
type = type_param,
ignore_I = ignore_I,
points_threshold = points_threshold,
info = info)
# with key antibiotics
x$newvar_first_isolate <- 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)
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)
} else {
# no key antibiotics
x$newvar_first_isolate <- 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)
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)
}
# first one as TRUE
@@ -379,10 +413,14 @@ first_isolate <- function(x,
}
if (!is.null(col_icu)) {
if (icu_exclude == TRUE) {
message(font_black("[Criterion] Exclude isolates from ICU.\n"))
message_("[Criterion] Exclude isolates from ICU.",
add_fn = font_black,
as_note = FALSE)
x[which(as.logical(x[, col_icu, drop = TRUE])), "newvar_first_isolate"] <- FALSE
} else {
message(font_black("[Criterion] Include isolates from ICU.\n"))
message_("[Criterion] Include isolates from ICU.",
add_fn = font_black,
as_note = FALSE)
}
}
@@ -391,18 +429,18 @@ first_isolate <- function(x,
# handle empty microorganisms
if (any(x$newvar_mo == "UNKNOWN", na.rm = TRUE) & info == TRUE) {
message(font_blue(paste0("NOTE: ", 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' (column `", font_bold(col_mo), "`)")))
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' (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(font_blue(paste0("NOTE: 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' (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' (column '", font_bold(col_mo), "')")
}
x[which(is.na(x$newvar_mo)), "newvar_first_isolate"] <- FALSE
@@ -411,11 +449,17 @@ first_isolate <- function(x,
rownames(x) <- NULL
if (info == TRUE) {
n_found <- base::sum(x$newvar_first_isolate, na.rm = TRUE)
p_found_total <- percentage(n_found / nrow(x[which(!is.na(x$newvar_mo)), , drop = FALSE]))
p_found_scope <- percentage(n_found / scope.size)
n_found <- sum(x$newvar_first_isolate, na.rm = TRUE)
p_found_total <- percentage(n_found / nrow(x[which(!is.na(x$newvar_mo)), , drop = FALSE]), digits = 1)
p_found_scope <- percentage(n_found / scope.size, digits = 1)
if (!p_found_total %like% "[.]") {
p_found_total <- gsub("%", ".0%", p_found_total, fixed = TRUE)
}
if (!p_found_scope %like% "[.]") {
p_found_scope <- gsub("%", ".0%", p_found_scope, fixed = TRUE)
}
# mark up number of found
n_found <- base::format(n_found, big.mark = big.mark, decimal.mark = decimal.mark)
n_found <- format(n_found, big.mark = big.mark, decimal.mark = decimal.mark)
if (p_found_total != p_found_scope) {
msg_txt <- paste0("=> Found ",
font_bold(paste0(n_found, " first ", weighted.notice, "isolates")),
@@ -425,7 +469,7 @@ first_isolate <- function(x,
font_bold(paste0(n_found, " first ", weighted.notice, "isolates")),
" (", p_found_total, " of total where a microbial ID was available)")
}
message(font_black(msg_txt))
message_(msg_txt, add_fn = font_black, as_note = FALSE)
}
x$newvar_first_isolate
@@ -439,6 +483,10 @@ filter_first_isolate <- function(x,
col_patient_id = NULL,
col_mo = NULL,
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(col_date, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_patient_id, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
subset(x, first_isolate(x = x,
col_date = col_date,
col_patient_id = col_patient_id,
@@ -454,6 +502,11 @@ filter_first_weighted_isolate <- function(x,
col_mo = NULL,
col_keyantibiotics = NULL,
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(col_date, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_patient_id, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
meet_criteria(col_keyantibiotics, allow_class = "character", has_length = 1, allow_NULL = TRUE, is_in = colnames(x))
y <- x
if (is.null(col_keyantibiotics)) {
# first try to look for it
@@ -469,8 +522,5 @@ filter_first_weighted_isolate <- function(x,
subset(x, first_isolate(x = y,
col_date = col_date,
col_patient_id = col_patient_id,
col_mo = col_mo,
col_keyantibiotics = col_keyantibiotics,
...))
col_patient_id = col_patient_id))
}

View File

@@ -1,28 +1,32 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' *G*-test for Count Data
#'
#' [g.test()] performs chi-squared contingency table tests and goodness-of-fit tests, just like [chisq.test()] but is more reliable (1). A *G*-test can be used to see whether the number of observations in each category fits a theoretical expectation (called a ***G*-test of goodness-of-fit**), or to see whether the proportions of one variable are different for different values of the other variable (called a ***G*-test of independence**).
#' @inheritSection lifecycle Questioning lifecycle
#' @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.
#'
@@ -30,18 +34,18 @@
#'
#' The p-value is computed from the asymptotic chi-squared distribution of the test statistic.
#'
#' In the contingency table case simulation is done by random sampling from the set of all contingency tables with given marginals, and works only if the marginals are strictly positive. Note that this is not the usual sampling situation assumed for a chi-squared test (like the *G*-test) but rather that for Fisher's exact test.
#' In the contingency table case simulation is done by random sampling from the set of all contingency tables with given marginals, and works only if the marginals are strictly positive. Note that this is not the usual sampling situation assumed for a chi-squared test (such as the *G*-test) but rather that for Fisher's exact test.
#'
#' In the goodness-of-fit case simulation is done by random sampling from the discrete distribution specified by `p`, each sample being of size `n = sum(x)`. This simulation is done in \R and may be slow.
#'
#' ## *G*-test of goodness-of-fit (likelihood ratio test)
#' ## *G*-test Of Goodness-of-Fit (Likelihood Ratio Test)
#' Use the *G*-test of goodness-of-fit when you have one nominal variable with two or more values (such as male and female, or red, pink and white flowers). You compare the observed counts of numbers of observations in each category with the expected counts, which you calculate using some kind of theoretical expectation (such as a 1:1 sex ratio or a 1:2:1 ratio in a genetic cross).
#'
#' If the expected number of observations in any category is too small, the *G*-test may give inaccurate results, and you should use an exact test instead ([fisher.test()]).
#'
#' The *G*-test of goodness-of-fit is an alternative to the chi-square test of goodness-of-fit ([chisq.test()]); each of these tests has some advantages and some disadvantages, and the results of the two tests are usually very similar.
#'
#' ## *G*-test of independence
#' ## *G*-test of Independence
#' Use the *G*-test of independence when you have two nominal variables, each with two or more possible values. You want to know whether the proportions for one variable are different among values of the other variable.
#'
#' It is also possible to do a *G*-test of independence with more than two nominal variables. For example, Jackson et al. (2013) also had data for children under 3, so you could do an analysis of old vs. young, thigh vs. arm, and reaction vs. no reaction, all analyzed together.
@@ -50,7 +54,7 @@
#'
#' The *G*-test of independence is an alternative to the chi-square test of independence ([chisq.test()]), and they will give approximately the same results.
#'
#' ## How the test works
#' ## How the Test Works
#' Unlike the exact test of goodness-of-fit ([fisher.test()]), the *G*-test does not directly calculate the probability of obtaining the observed results or something more extreme. Instead, like almost all statistical tests, the *G*-test has an intermediate step; it uses the data to calculate a test statistic that measures how far the observed data are from the null expectation. You then use a mathematical relationship, in this case the chi-square distribution, to estimate the probability of obtaining that value of the test statistic.
#'
#' The *G*-test uses the log of the ratio of two likelihoods as the test statistic, which is why it is also called a likelihood ratio test or log-likelihood ratio test. The formula to calculate a *G*-statistic is:
@@ -72,7 +76,7 @@
#' - 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!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # = EXAMPLE 1 =
#' # Shivrain et al. (2006) crossed clearfield rice (which are resistant
@@ -140,7 +144,7 @@ g.test <- function(x,
DNAME <- paste(paste(DNAME, collapse = "\n"), "and",
paste(DNAME2, collapse = "\n"))
}
if (any(x < 0) || anyNA(x))
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)
stop("at least one entry of 'x' must be positive")
@@ -196,7 +200,7 @@ g.test <- function(x,
if (any(E < 5) && is.finite(PARAMETER))
warning("G-statistic approximation may be incorrect due to E < 5")
structure(list(statistic = STATISTIC, parameter = 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")

View File

@@ -1,28 +1,32 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' PCA biplot with `ggplot2`
#' 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 Maturing lifecycle
#' @inheritSection lifecycle Maturing 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()].
@@ -43,15 +47,16 @@
#' @param arrows_textangled a logical whether the text at the end of the arrows should be angled
#' @param arrows_alpha the alpha (transparency) of the arrows and their text
#' @param base_textsize the text size for all plot elements except the labels and arrows
#' @param ... Parameters passed on to functions
#' @param ... Arguments passed on to functions
#' @source The [ggplot_pca()] function is based on the `ggbiplot()` function from the `ggbiplot` package by Vince Vu, as found on GitHub: <https://github.com/vqv/ggbiplot> (retrieved: 2 March 2020, their latest commit: [`7325e88`](https://github.com/vqv/ggbiplot/commit/7325e880485bea4c07465a0304c470608fffb5d9); 12 February 2015).
#'
#' As per their GPL-2 licence that demands documentation of code changes, the changes made based on the source code were:
#' 1. Rewritten code to remove the dependency on packages `plyr`, `scales` and `grid`
#' 2. Parametrised more options, like arrow and ellipse settings
#' 3. Added total amount of explained variance as a caption in the plot
#' 4. Cleaned all syntax based on the `lintr` package and added integrity checks
#' 5. Updated documentation
#' 3. Hardened all input possibilities by defining the exact type of user input for every argument
#' 4. Added total amount of explained variance as a caption in the plot
#' 5. Cleaned all syntax based on the `lintr` package, fixed grammatical errors and added integrity checks
#' 6. Updated documentation
#' @details The colours for labels and points can be changed by adding another scale layer for colour, like `scale_colour_viridis_d()` or `scale_colour_brewer()`.
#' @rdname ggplot_pca
#' @export
@@ -60,8 +65,7 @@
#' # See ?example_isolates.
#'
#' # See ?pca for more info about Principal Component Analysis (PCA).
#' \dontrun{
#' library(dplyr)
#' if (require("dplyr")) {
#' pca_model <- example_isolates %>%
#' filter(mo_genus(mo) == "Staphylococcus") %>%
#' group_by(species = mo_shortname(mo)) %>%
@@ -82,7 +86,7 @@
#' }
ggplot_pca <- function(x,
choices = 1:2,
scale = TRUE,
scale = 1,
pc.biplot = TRUE,
labels = NULL,
labels_textsize = 3,
@@ -104,22 +108,27 @@ ggplot_pca <- function(x,
...) {
stop_ifnot_installed("ggplot2")
stop_ifnot(length(choices) == 2, "`choices` must be of length 2")
stop_ifnot(is.logical(arrows), "`arrows` must be TRUE or FALSE")
stop_ifnot(is.logical(arrows_textangled), "`arrows_textangled` must be TRUE or FALSE")
stop_ifnot(is.logical(ellipse), "`ellipse` must be TRUE or FALSE")
stop_ifnot(is.logical(pc.biplot), "`pc.biplot` must be TRUE or FALSE")
stop_ifnot(is.logical(scale), "`scale` must be TRUE or FALSE")
stop_ifnot(is.numeric(arrows_alpha), "`arrows_alpha` must be numeric")
stop_ifnot(is.numeric(arrows_size), "`arrows_size` must be numeric")
stop_ifnot(is.numeric(arrows_textsize), "`arrows_textsize` must be numeric")
stop_ifnot(is.numeric(base_textsize), "`base_textsize` must be numeric")
stop_ifnot(is.numeric(choices), "`choices` must be numeric")
stop_ifnot(is.numeric(ellipse_alpha), "`ellipse_alpha` must be numeric")
stop_ifnot(is.numeric(ellipse_prob), "`ellipse_prob` must be numeric")
stop_ifnot(is.numeric(ellipse_size), "`ellipse_size` must be numeric")
stop_ifnot(is.numeric(labels_text_placement), "`labels_text_placement` must be numeric")
stop_ifnot(is.numeric(labels_textsize), "`labels_textsize` must be numeric")
meet_criteria(x, allow_class = c("prcomp", "princomp", "PCA", "lda"))
meet_criteria(choices, allow_class = c("numeric", "integer"), has_length = 2)
meet_criteria(scale, allow_class = c("numeric", "integer", "logical"), has_length = 1)
meet_criteria(pc.biplot, allow_class = "logical", has_length = 1)
meet_criteria(labels, allow_class = "character", allow_NULL = TRUE)
meet_criteria(labels_textsize, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(labels_text_placement, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(groups, allow_class = "character", allow_NULL = TRUE)
meet_criteria(ellipse, allow_class = "logical", has_length = 1)
meet_criteria(ellipse_prob, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(ellipse_size, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(ellipse_alpha, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(points_size, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(points_alpha, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(arrows, allow_class = "logical", has_length = 1)
meet_criteria(arrows_colour, allow_class = "character", has_length = 1)
meet_criteria(arrows_size, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(arrows_textsize, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(arrows_textangled, allow_class = "logical", has_length = 1)
meet_criteria(arrows_alpha, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(base_textsize, allow_class = c("numeric", "integer"), has_length = 1)
calculations <- pca_calculations(pca_model = x,
groups = groups,
@@ -297,19 +306,20 @@ pca_calculations <- function(pca_model,
d <- pca_model$svd
u <- predict(pca_model)$x / nobs.factor
v <- pca_model$scaling
d.total <- sum(d ^ 2)
} else {
stop("Expected a object of class prcomp, princomp, PCA, or lda")
stop("Expected an object of class prcomp, princomp, PCA, or lda")
}
# Scores
choices <- pmin(choices, ncol(u))
obs.scale <- 1 - as.integer(scale)
df.u <- as.data.frame(sweep(u[, choices], 2, d[choices] ^ obs.scale, FUN = "*"))
df.u <- as.data.frame(sweep(u[, choices], 2, d[choices] ^ obs.scale, FUN = "*"),
stringsAsFactors = FALSE)
# Directions
v <- sweep(v, 2, d ^ as.integer(scale), FUN = "*")
df.v <- as.data.frame(v[, choices])
df.v <- as.data.frame(v[, choices],
stringsAsFactors = FALSE)
names(df.u) <- c("xvar", "yvar")
names(df.v) <- names(df.u)
@@ -347,7 +357,8 @@ pca_calculations <- function(pca_model,
if (nrow(x) <= 2) {
return(data.frame(X1 = numeric(0),
X2 = numeric(0),
groups = character(0)))
groups = character(0),
stringsAsFactors = FALSE))
}
sigma <- var(cbind(x$xvar, x$yvar))
mu <- c(mean(x$xvar), mean(x$yvar))

View File

@@ -1,29 +1,33 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' AMR plots with `ggplot2`
#' AMR Plots with `ggplot2`
#'
#' Use these functions to create bar plots for antimicrobial resistance analysis. All functions rely on [ggplot2][ggplot2::ggplot()] functions.
#' @inheritSection lifecycle Maturing lifecycle
#' @param data a [`data.frame`] with column(s) of class [`rsi`] (see [as.rsi()])
#' @inheritSection lifecycle Maturing 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
#' @param fill variable to categorise using the plots legend, either `"antibiotic"` (default) or `"interpretation"` or a grouping variable
@@ -32,7 +36,7 @@
#' @param facet variable to split plots by, either `"interpretation"` (default) or `"antibiotic"` or a grouping variable
#' @inheritParams proportion
#' @param nrow (when using `facet`) number of rows
#' @param colours a named vector with colours for the bars. The names must be one or more of: S, SI, I, IR, R or be `FALSE` to use default [ggplot2][[ggplot2::ggplot()] colours.
#' @param colours a named vector with colours for the bars. The names must be one or more of: S, SI, I, IR, R or be `FALSE` to use default [ggplot2][ggplot2::ggplot()] colours.
#' @param datalabels show datalabels using [labels_rsi_count()]
#' @param datalabels.size size of the datalabels
#' @param datalabels.colour colour of the datalabels
@@ -41,10 +45,10 @@
#' @param caption text to show as caption of the plot
#' @param x.title text to show as x axis description
#' @param y.title text to show as y axis description
#' @param ... other parameters passed on to [geom_rsi()]
#' @details At default, the names of antibiotics will be shown on the plots using [ab_name()]. This can be set with the `translate_ab` parameter. See [count_df()].
#' @param ... other arguments passed on to [geom_rsi()]
#' @details At default, the names of antibiotics will be shown on the plots using [ab_name()]. This can be set with the `translate_ab` argument. See [count_df()].
#'
#' ## The functions
#' ## The Functions
#' [geom_rsi()] will take any variable from the data that has an [`rsi`] class (created with [as.rsi()]) using [rsi_df()] and will plot bars with the percentage R, I and S. The default behaviour is to have the bars stacked and to have the different antibiotics on the x axis.
#'
#' [facet_rsi()] creates 2d plots (at default based on S/I/R) using [ggplot2::facet_wrap()].
@@ -57,10 +61,10 @@
#'
#' [labels_rsi_count()] print datalabels on the bars with percentage and amount of isolates using [ggplot2::geom_text()].
#'
#' [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.
#' [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!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' if (require("ggplot2") & require("dplyr")) {
#'
@@ -87,7 +91,7 @@
#' select(AMX, NIT, FOS, TMP, CIP) %>%
#' ggplot_rsi(datalabels = FALSE)
#'
#' # add other ggplot2 parameters as you like:
#' # add other ggplot2 arguments as you like:
#' example_isolates %>%
#' select(AMX, NIT, FOS, TMP, CIP) %>%
#' ggplot_rsi(width = 0.5,
@@ -102,14 +106,13 @@
#'
#' }
#'
#' \dontrun{
#'
#' \donttest{
#' # resistance of ciprofloxacine per age group
#' example_isolates %>%
#' mutate(first_isolate = first_isolate(.)) %>%
#' filter(first_isolate == TRUE,
#' mo == as.mo("E. coli")) %>%
#' # `age_group` is also a function of this package:
#' # age_groups() is also a function in this AMR package:
#' group_by(age_group = age_groups(age)) %>%
#' select(age_group,
#' CIP) %>%
@@ -118,7 +121,8 @@
#' # for colourblind mode, use divergent colours from the viridis package:
#' example_isolates %>%
#' select(AMX, NIT, FOS, TMP, CIP) %>%
#' ggplot_rsi() + scale_fill_viridis_d()
#' ggplot_rsi() +
#' scale_fill_viridis_d()
#' # a shorter version which also adjusts data label colours:
#' example_isolates %>%
#' select(AMX, NIT, FOS, TMP, CIP) %>%
@@ -147,6 +151,7 @@ ggplot_rsi <- function(data,
translate_ab = "name",
combine_SI = TRUE,
combine_IR = FALSE,
minimum = 30,
language = get_locale(),
nrow = NULL,
colours = c(S = "#61a8ff",
@@ -156,7 +161,7 @@ ggplot_rsi <- function(data,
R = "#ff6961"),
datalabels = TRUE,
datalabels.size = 2.5,
datalabels.colour = "gray15",
datalabels.colour = "grey15",
title = NULL,
subtitle = NULL,
caption = NULL,
@@ -165,10 +170,29 @@ ggplot_rsi <- function(data,
...) {
stop_ifnot_installed("ggplot2")
x <- x[1]
facet <- facet[1]
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)
meet_criteria(x, allow_class = "character", has_length = 1)
meet_criteria(fill, allow_class = "character", has_length = 1)
meet_criteria(facet, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(breaks, allow_class = c("numeric", "integer"))
meet_criteria(limits, allow_class = c("numeric", "integer"), has_length = 2, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE)
meet_criteria(combine_SI, allow_class = "logical", has_length = 1)
meet_criteria(combine_IR, allow_class = "logical", has_length = 1)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(nrow, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE)
meet_criteria(colours, allow_class = c("character", "logical"))
meet_criteria(datalabels, allow_class = "logical", has_length = 1)
meet_criteria(datalabels.size, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(datalabels.colour, allow_class = "character", has_length = 1)
meet_criteria(title, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(subtitle, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(caption, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(x.title, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(y.title, allow_class = "character", has_length = 1, allow_NULL = TRUE)
# we work with aes_string later on
x_deparse <- deparse(substitute(x))
if (x_deparse != "x") {
@@ -194,14 +218,15 @@ ggplot_rsi <- function(data,
p <- ggplot2::ggplot(data = data) +
geom_rsi(position = position, x = x, fill = fill, translate_ab = translate_ab,
minimum = minimum, language = language,
combine_SI = combine_SI, combine_IR = combine_IR, ...) +
theme_rsi()
if (fill == "interpretation") {
# set RSI colours
if (isFALSE(colours) & missing(datalabels.colour)) {
# set datalabel colour to middle gray
datalabels.colour <- "gray50"
# set datalabel colour to middle grey
datalabels.colour <- "grey50"
}
p <- p + scale_rsi_colours(colours = colours)
}
@@ -215,6 +240,8 @@ ggplot_rsi <- function(data,
p <- p + labels_rsi_count(position = position,
x = x,
translate_ab = translate_ab,
minimum = minimum,
language = language,
combine_SI = combine_SI,
combine_IR = combine_IR,
datalabels.size = datalabels.size,
@@ -240,13 +267,22 @@ geom_rsi <- function(position = NULL,
x = c("antibiotic", "interpretation"),
fill = "interpretation",
translate_ab = "name",
minimum = 30,
language = get_locale(),
combine_SI = TRUE,
combine_IR = FALSE,
...) {
x <- x[1]
stop_ifnot_installed("ggplot2")
stop_if(is.data.frame(position), "`position` is invalid. Did you accidentally use '%>%' instead of '+'?")
meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE)
meet_criteria(x, allow_class = "character", has_length = 1)
meet_criteria(fill, allow_class = "character", has_length = 1)
meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(combine_SI, allow_class = "logical", has_length = 1)
meet_criteria(combine_IR, allow_class = "logical", has_length = 1)
y <- "value"
if (missing(position) | is.null(position)) {
@@ -257,8 +293,6 @@ geom_rsi <- function(position = NULL,
position <- ggplot2::position_fill(vjust = 0.5, reverse = TRUE)
}
x <- x[1]
# we work with aes_string later on
x_deparse <- deparse(substitute(x))
if (x_deparse != "x") {
@@ -280,6 +314,7 @@ geom_rsi <- function(position = NULL,
rsi_df(data = x,
translate_ab = translate_ab,
language = language,
minimum = minimum,
combine_SI = combine_SI,
combine_IR = combine_IR)
})
@@ -289,10 +324,10 @@ geom_rsi <- function(position = NULL,
#' @rdname ggplot_rsi
#' @export
facet_rsi <- function(facet = c("interpretation", "antibiotic"), nrow = NULL) {
stop_ifnot_installed("ggplot2")
facet <- facet[1]
stop_ifnot_installed("ggplot2")
meet_criteria(facet, allow_class = "character", has_length = 1)
meet_criteria(nrow, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE)
# we work with aes_string later on
facet_deparse <- deparse(substitute(facet))
@@ -316,6 +351,8 @@ facet_rsi <- function(facet = c("interpretation", "antibiotic"), nrow = NULL) {
#' @export
scale_y_percent <- function(breaks = seq(0, 1, 0.1), limits = NULL) {
stop_ifnot_installed("ggplot2")
meet_criteria(breaks, allow_class = c("numeric", "integer"))
meet_criteria(limits, allow_class = c("numeric", "integer"), has_length = 2, allow_NULL = TRUE, allow_NA = TRUE)
if (all(breaks[breaks != 0] > 1)) {
breaks <- breaks / 100
@@ -333,6 +370,8 @@ scale_rsi_colours <- function(colours = c(S = "#61a8ff",
IR = "#ff6961",
R = "#ff6961")) {
stop_ifnot_installed("ggplot2")
meet_criteria(colours, allow_class = c("character", "logical"))
# previous colour: palette = "RdYlGn"
# previous colours: values = c("#b22222", "#ae9c20", "#7cfc00")
@@ -365,11 +404,23 @@ theme_rsi <- function() {
labels_rsi_count <- function(position = NULL,
x = "antibiotic",
translate_ab = "name",
minimum = 30,
language = get_locale(),
combine_SI = TRUE,
combine_IR = FALSE,
datalabels.size = 3,
datalabels.colour = "gray15") {
datalabels.colour = "grey15") {
stop_ifnot_installed("ggplot2")
meet_criteria(position, allow_class = "character", has_length = 1, is_in = c("fill", "stack", "dodge"), allow_NULL = TRUE)
meet_criteria(x, allow_class = "character", has_length = 1)
meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(combine_SI, allow_class = "logical", has_length = 1)
meet_criteria(combine_IR, allow_class = "logical", has_length = 1)
meet_criteria(datalabels.size, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(datalabels.colour, allow_class = "character", has_length = 1)
if (is.null(position)) {
position <- "fill"
}
@@ -389,12 +440,14 @@ labels_rsi_count <- function(position = NULL,
transformed <- rsi_df(data = x,
translate_ab = translate_ab,
combine_SI = combine_SI,
combine_IR = combine_IR)
combine_IR = combine_IR,
minimum = minimum,
language = language)
transformed$gr <- transformed[, x_name, drop = TRUE]
transformed %>%
group_by(gr) %>%
mutate(lbl = paste0("n=", isolates)) %>%
ungroup() %>%
select(-gr)
transformed %pm>%
pm_group_by(gr) %pm>%
pm_mutate(lbl = paste0("n=", isolates)) %pm>%
pm_ungroup() %pm>%
pm_select(-gr)
})
}

View File

@@ -1,43 +1,57 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
globalVariables(c("ab",
globalVariables(c(".rowid",
"ab",
"ab_txt",
"angle",
"antibiotic",
"antibiotics",
"atc_group1",
"atc_group2",
"code",
"data",
"dosage",
"dose",
"dose_times",
"fullname",
"fullname_lower",
"g_species",
"genus",
"gr",
"group",
"guideline",
"hjust",
"input",
"intrinsic_resistant",
"isolates",
"lang",
"language",
"lookup",
"method",
"microorganism",
"microorganisms",
"microorganisms.codes",
"microorganisms.old",
@@ -49,7 +63,11 @@ globalVariables(c("ab",
"old_name",
"pattern",
"R",
"reference.rule",
"reference.rule_group",
"reference.version",
"rsi_translation",
"rowid",
"rule_group",
"rule_name",
"se_max",
@@ -58,8 +76,10 @@ globalVariables(c("ab",
"species_id",
"total",
"txt",
"type",
"value",
"varname",
"xvar",
"y",
"year",
"yvar"))

View File

@@ -1,35 +1,39 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Guess antibiotic column
#' 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 Maturing lifecycle
#' @param x a [`data.frame`]
#' @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
#' @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 precendence 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. **Longer columns names take precedence over shorter column names.**
#' @return A column name of `x`, or `NULL` when no result is found.
#' @export
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' df <- data.frame(amox = "S",
#' tetr = "R")
@@ -40,7 +44,7 @@
#' # [1] "tetr"
#'
#' guess_ab_col(df, "J01AA07", verbose = TRUE)
#' # NOTE: Using column `tetr` as input for `J01AA07` (tetracycline).
#' # NOTE: Using column 'tetr' as input for J01AA07 (tetracycline).
#' # [1] "tetr"
#'
#' # WHONET codes
@@ -59,16 +63,13 @@
#' guess_ab_col(df, "ampicillin")
#' # [1] "AMP_ED20"
guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE) {
meet_criteria(x, allow_class = "data.frame", allow_NULL = TRUE)
meet_criteria(search_string, allow_class = "character", has_length = 1, allow_NULL = TRUE)
meet_criteria(verbose, allow_class = "logical", has_length = 1)
if (is.null(x) & is.null(search_string)) {
return(as.name("guess_ab_col"))
}
stop_ifnot(is.data.frame(x), "`x` must be a data.frame")
if (length(search_string) > 1) {
warning("argument 'search_string' has length > 1 and only the first element will be used")
search_string <- search_string[1]
}
search_string <- as.character(search_string)
if (search_string %in% colnames(x)) {
ab_result <- search_string
@@ -82,7 +83,7 @@ guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE) {
} else {
# sort colnames on length - longest first
cols <- colnames(x[, x %>% colnames() %>% nchar() %>% order() %>% rev()])
cols <- colnames(x[, x %pm>% colnames() %pm>% nchar() %pm>% order() %pm>% rev()])
df_trans <- data.frame(cols = cols,
abs = suppressWarnings(as.ab(cols)),
stringsAsFactors = FALSE)
@@ -93,14 +94,16 @@ guess_ab_col <- function(x = NULL, search_string = NULL, verbose = FALSE) {
if (length(ab_result) == 0) {
if (verbose == TRUE) {
message(paste0("No column found as input for `", search_string,
"` (", ab_name(search_string, language = NULL, tolower = TRUE), ")."))
message_("No column found as input for ", search_string,
" (", ab_name(search_string, language = NULL, tolower = TRUE), ").",
add_fn = font_black,
as_note = FALSE)
}
return(NULL)
} else {
if (verbose == TRUE) {
message(font_blue(paste0("NOTE: 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)
}
@@ -110,50 +113,65 @@ get_column_abx <- function(x,
soft_dependencies = NULL,
hard_dependencies = NULL,
verbose = FALSE,
info = TRUE,
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(soft_dependencies, allow_class = "character", allow_NULL = TRUE)
meet_criteria(hard_dependencies, allow_class = "character", allow_NULL = TRUE)
meet_criteria(verbose, allow_class = "logical", has_length = 1)
meet_criteria(info, allow_class = "logical", has_length = 1)
message(font_blue("NOTE: Auto-guessing columns suitable for analysis"), appendLF = FALSE)
if (info == TRUE) {
message_("Auto-guessing columns suitable for analysis", appendLF = FALSE, as_note = FALSE)
}
x <- as.data.frame(x, stringsAsFactors = FALSE)
if (NROW(x) > 10000) {
# only test maximum of 10,000 values per column
message(font_blue(paste0(" (using only ", font_bold("the first 10,000 rows"), ")...")), appendLF = FALSE)
if (info == TRUE) {
message_(" (using only ", font_bold("the first 10,000 rows"), ")...",
appendLF = FALSE,
as_note = FALSE)
}
x <- x[1:10000, , drop = FALSE]
} else {
message(font_blue("..."), appendLF = FALSE)
} else if (info == TRUE) {
message_("...", appendLF = FALSE, as_note = FALSE)
}
x_bak <- x
# only check columns that are a valid AB code, ATC code, name, abbreviation or synonym,
# or already have the rsi class (as.rsi)
# and that have no more than 50% invalid values
# or already have the <rsi> class (as.rsi)
# and that they have no more than 50% invalid values
vectr_antibiotics <- unique(toupper(unlist(antibiotics[, c("ab", "atc", "name", "abbreviations", "synonyms")])))
vectr_antibiotics <- vectr_antibiotics[!is.na(vectr_antibiotics) & nchar(vectr_antibiotics) >= 3]
x_columns <- sapply(colnames(x), function(col, df = x_bak) {
if (toupper(col) %in% vectr_antibiotics |
is.rsi(as.data.frame(df)[, col]) |
is.rsi.eligible(as.data.frame(df)[, col], threshold = 0.5)) {
x_columns <- vapply(FUN.VALUE = character(1), colnames(x), function(col, df = x) {
if (toupper(col) %in% vectr_antibiotics ||
is.rsi(x[, col, drop = TRUE]) ||
is.rsi.eligible(x[, col, drop = TRUE], threshold = 0.5)
) {
return(col)
} else {
return(NA_character_)
}
})
x_columns <- x_columns[!is.na(x_columns)]
x <- x[, x_columns, drop = FALSE] # without drop = TRUE, x will become a vector when x_columns is length 1
df_trans <- data.frame(colnames = colnames(x),
abcode = suppressWarnings(as.ab(colnames(x))))
df_trans <- df_trans[!is.na(df_trans$abcode), ]
abcode = suppressWarnings(as.ab(colnames(x), info = FALSE)),
stringsAsFactors = FALSE)
df_trans <- df_trans[!is.na(df_trans$abcode), , drop = FALSE]
x <- as.character(df_trans$colnames)
names(x) <- df_trans$abcode
# add from self-defined dots (...):
# such as get_column_abx(example_isolates %>% rename(thisone = AMX), amox = "thisone")
# such as get_column_abx(example_isolates %pm>% rename(thisone = AMX), amox = "thisone")
dots <- list(...)
if (length(dots) > 0) {
newnames <- suppressWarnings(as.ab(names(dots)))
newnames <- suppressWarnings(as.ab(names(dots), info = FALSE))
if (any(is.na(newnames))) {
warning("Invalid antibiotic reference(s): ", toString(names(dots)[is.na(newnames)]),
call. = FALSE, immediate. = TRUE)
warning_("Invalid antibiotic reference(s): ", toString(names(dots)[is.na(newnames)]),
call = FALSE,
immediate = TRUE)
}
# turn all NULLs to NAs
dots <- unlist(lapply(dots, function(x) if (is.null(x)) NA else x))
@@ -166,34 +184,38 @@ get_column_abx <- function(x,
}
if (length(x) == 0) {
message(font_blue("No columns found."))
if (info == TRUE) {
message_("No columns found.")
}
return(x)
}
# sort on name
x <- x[order(names(x), x)]
duplicates <- c(x[base::duplicated(x)], x[base::duplicated(names(x))])
duplicates <- c(x[duplicated(x)], x[duplicated(names(x))])
duplicates <- duplicates[unique(names(duplicates))]
x <- c(x[!names(x) %in% names(duplicates)], duplicates)
x <- x[order(names(x), x)]
# succeeded with auto-guessing
message(font_blue("OK."))
for (i in seq_len(length(x))) {
if (verbose == TRUE & !names(x[i]) %in% names(duplicates)) {
message(font_blue(paste0("NOTE: Using column `", font_bold(x[i]), "` as input for `", names(x)[i],
"` (", ab_name(names(x)[i], tolower = TRUE, language = NULL), ").")))
}
if (names(x[i]) %in% names(duplicates)) {
warning(font_red(paste0("Using column `", font_bold(x[i]), "` as input for `", names(x)[i],
"` (", ab_name(names(x)[i], tolower = TRUE, language = NULL),
"), although it was matched for multiple antibiotics or columns.")),
call. = FALSE,
immediate. = verbose)
}
if (info == TRUE) {
message_(" OK.", add_fn = list(font_green, font_bold), as_note = FALSE)
}
for (i in seq_len(length(x))) {
if (info == TRUE & verbose == TRUE & !names(x[i]) %in% names(duplicates)) {
message_("Using column '", font_bold(x[i]), "' as input for ", names(x)[i],
" (", ab_name(names(x)[i], tolower = TRUE, language = NULL), ").")
}
if (info == TRUE & names(x[i]) %in% names(duplicates)) {
warning_(paste0("Using column '", font_bold(x[i]), "' as input for ", names(x)[i],
" (", ab_name(names(x)[i], tolower = TRUE, language = NULL),
"), although it was matched for multiple antibiotics or columns."),
add_fn = font_red,
call = FALSE,
immediate = verbose)
}
}
if (!is.null(hard_dependencies)) {
hard_dependencies <- unique(hard_dependencies)
@@ -206,14 +228,14 @@ get_column_abx <- function(x,
}
if (!is.null(soft_dependencies)) {
soft_dependencies <- unique(soft_dependencies)
if (!all(soft_dependencies %in% names(x))) {
if (info == TRUE & !all(soft_dependencies %in% names(x))) {
# missing a soft dependency may lower the reliability
missing <- soft_dependencies[!soft_dependencies %in% names(x)]
missing_txt <- paste(paste0(ab_name(missing, tolower = TRUE, language = NULL),
missing_msg <- paste(paste0(ab_name(missing, tolower = TRUE, language = NULL),
" (", font_bold(missing, collapse = NULL), ")"),
collapse = ", ")
message(font_blue("NOTE: Reliability would be improved if these antimicrobial results would be available too:",
missing_txt))
message_("Reliability would be improved if these antimicrobial results would be available too: ",
missing_msg)
}
}
x
@@ -226,8 +248,8 @@ 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: ",
paste(missing, collapse = ", ")),
immediate. = TRUE,
call. = FALSE)
warning_(paste0("Introducing NAs since", any_txt[1], " these antimicrobials ", any_txt[2], " required: ",
paste(missing, collapse = ", ")),
immediate = TRUE,
call = FALSE)
}

203
R/isolate_identifier.R Normal file
View File

@@ -0,0 +1,203 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Create Identifier of an Isolate
#'
#' This function will paste the microorganism code with all antimicrobial results into one string for each row in a data set. This is useful to compare isolates, e.g. between institutions or regions, when there is no genotyping available.
#' @inheritSection lifecycle Experimental Lifecycle
#' @inheritParams eucast_rules
#' @param cols_ab a character vector of column names of `x`, or (a combination with) an [antibiotic selector function]([ab_class()]), such as [carbapenems()] and [aminoglycosides()]
#' @rdname isolate_identifier
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # automatic selection of microorganism and antibiotics (i.e., all <rsi> columns, see ?as.rsi)
#' x <- isolate_identifier(example_isolates)
#'
#' # ignore microorganism codes, only use antimicrobial results
#' x <- isolate_identifier(example_isolates, col_mo = FALSE, cols_ab = c("AMX", "TZP", "GEN", "TOB"))
#'
#' # select antibiotics from certain antibiotic classes
#' x <- isolate_identifier(example_isolates, cols_ab = c(carbapenems(), aminoglycosides()))
isolate_identifier <- function(x, col_mo = NULL, cols_ab = NULL) {
if (is.null(col_mo)) {
col_mo <- search_type_in_df(x, "mo")
if (is.null(col_mo)) {
# no column found, then ignore the argument
col_mo <- FALSE
}
}
if (isFALSE(col_mo)) {
# is FALSE then ignore mo column
x$col_mo <- ""
col_mo <- "col_mo"
} else if (!is.null(col_mo)) {
x[, col_mo] <- paste0(as.mo(x[, col_mo, drop = TRUE]), "|")
}
cols_ab <- deparse(substitute(cols_ab)) # support ab class selectors: isolate_identifier(x, cols_ab = carbapenems())
if (identical(cols_ab, "NULL")) {
cols_ab <- colnames(x)[vapply(FUN.VALUE = logical(1), x, is.rsi)]
} else {
cols_ab <- tryCatch(colnames(x[, eval(parse(text = cols_ab), envir = parent.frame())]),
# tryCatch adds 4 calls, so total is -5
error = function(e) stop_(e$message, call = -5))
}
# cope with empty values
if (length(cols_ab) == 0 && all(x[, col_mo, drop = TRUE] == "", na.rm = TRUE)) {
warning_("in isolate_identifier(): no column with microorganisms and no columns with antimicrobial agents found", call = FALSE)
} else if (length(cols_ab) == 0) {
warning_("in isolate_identifier(): no columns with antimicrobial agents found", call = FALSE)
}
out <- x[, c(col_mo, cols_ab), drop = FALSE]
out <- do.call(paste, c(out, sep = ""))
out <- gsub("NA", ".", out, fixed = TRUE)
out <- set_clean_class(out, new_class = c("isolate_identifier", "character"))
attr(out, "ab") <- cols_ab
out
}
#' @method all.equal isolate_identifier
#' @inheritParams base::all.equal
#' @param ignore_empty_results a logical to indicate whether empty results must be ignored, so that only values R, S and I will be compared
#' @rdname isolate_identifier
#' @export
all.equal.isolate_identifier <- function(target, current, ignore_empty_results = TRUE, ...) {
meet_criteria(target, allow_class = "isolate_identifier")
meet_criteria(current, allow_class = "isolate_identifier")
meet_criteria(ignore_empty_results, allow_class = "logical", has_length = 1)
if (isTRUE(all.equal.character(target, current))) {
return(TRUE)
}
# vectorise over both target and current
if (length(target) > 1 && length(current) == 1) {
current <- rep(current, length(target))
} else if (length(current) > 1 && length(target) == 1) {
target <- rep(target, length(current))
}
stop_if(length(target) != length(current),
"length of `target` and `current` must be the same, or one must be 1")
get_vector <- function(x) {
if (grepl("|", x, fixed = TRUE)) {
mo <- gsub("(.*)\\|.*", "\\1", x)
} else {
mo <- NULL
}
if (grepl("|", x, fixed = TRUE)) {
ab <- gsub(".*\\|(.*)", "\\1", x)
} else {
ab <- x
}
ab <- strsplit(ab, "")[[1L]]
if (is.null(mo)) {
out <- as.character(ab)
names(out) <- attributes(x)$ab
} else {
out <- as.character(c(mo, ab))
names(out) <- c("mo", attributes(x)$ab)
}
out
}
# run it
for (i in seq_len(length(target))) {
if (i == 1) {
df <- data.frame(object = paste0(c("target[", "current["), i, "]"))
}
trgt <- get_vector(target[i])
crnt <- get_vector(current[i])
if (ignore_empty_results == TRUE) {
diff <- names(trgt[trgt != crnt & trgt != "." & crnt != "."])
} else {
diff <- names(trgt[trgt != crnt])
}
}
stop("THIS FUNCTION IS WORK IN PROGRESS AND NOT AVAILABLE IN THIS BETA VERSION")
}
#' @method print isolate_identifier
#' @export
#' @noRd
print.isolate_identifier <- function(x, ...) {
print(as.character(x), ...)
}
#' @method [ isolate_identifier
#' @export
#' @noRd
"[.isolate_identifier" <- function(x, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
#' @method [[ isolate_identifier
#' @export
#' @noRd
"[[.isolate_identifier" <- function(x, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
#' @method [<- isolate_identifier
#' @export
#' @noRd
"[<-.isolate_identifier" <- function(i, j, ..., value) {
y <- NextMethod()
attributes(y) <- attributes(i)
y
}
#' @method [[<- isolate_identifier
#' @export
#' @noRd
"[[<-.isolate_identifier" <- function(i, j, ..., value) {
y <- NextMethod()
attributes(y) <- attributes(i)
y
}
#' @method c isolate_identifier
#' @export
#' @noRd
c.isolate_identifier <- function(x, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
#' @method unique isolate_identifier
#' @export
#' @noRd
unique.isolate_identifier <- function(x, incomparables = FALSE, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}

View File

@@ -1,70 +1,89 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Join [microorganisms] to a data set
#' Join [microorganisms] to a Data Set
#'
#' Join the data set [microorganisms] easily to an existing table or character vector.
#' @inheritSection lifecycle Stable lifecycle
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname join
#' @name join
#' @aliases join inner_join
#' @param x existing table to join, or character vector
#' @param by a variable to join by - if left empty will search for a column with class [`mo`] (created with [as.mo()]) or will be `"mo"` if that column name exists in `x`, could otherwise be a column name of `x` with values that exist in `microorganisms$mo` (like `by = "bacteria_id"`), or another column in [microorganisms] (but then it should be named, like `by = c("my_genus_species" = "fullname")`)
#' @param by a variable to join by - if left empty will search for a column with class [`mo`] (created with [as.mo()]) or will be `"mo"` if that column name exists in `x`, could otherwise be a column name of `x` with values that exist in `microorganisms$mo` (such as `by = "bacteria_id"`), or another column in [microorganisms] (but then it should be named, like `by = c("bacteria_id" = "fullname")`)
#' @param suffix if there are non-joined duplicate variables in `x` and `y`, these suffixes will be added to the output to disambiguate them. Should be a character vector of length 2.
#' @param ... ignored
#' @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.
#' @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.
#'
#' These functions rely on [merge()], a base R function to do joins.
#' @inheritSection AMR Read more on our website!
#' If the `dplyr` package is installed, their join functions will be used. Otherwise, the much slower [merge()] function from base R will be used.
#' @inheritSection AMR Read more on Our Website!
#' @export
#' @examples
#' left_join_microorganisms(as.mo("K. pneumoniae"))
#' left_join_microorganisms("B_KLBSL_PNE")
#'
#' \dontrun{
#' library(dplyr)
#' example_isolates %>% left_join_microorganisms()
#'
#' 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", ""), ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
meet_criteria(suffix, allow_class = "character", has_length = 2)
check_dataset_integrity()
check_groups_before_join(x, "inner_join_microorganisms")
x <- check_groups_before_join(x, "inner_join_microorganisms")
checked <- joins_check_df(x, by)
x_class <- get_prejoined_class(x)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
inner_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
# use dplyr if available - it's much faster
dplyr_inner <- import_fn("inner_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_inner)) {
join <- suppressWarnings(
dplyr_inner(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
} else {
join <- suppressWarnings(
pm_inner_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
}
if (NROW(join) > NROW(x)) {
warning("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
warning_("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
}
class(join) <- x_class
join
@@ -73,17 +92,29 @@ inner_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
#' @rdname join
#' @export
left_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
meet_criteria(suffix, allow_class = "character", has_length = 2)
check_dataset_integrity()
check_groups_before_join(x, "left_join_microorganisms")
x <- check_groups_before_join(x, "left_join_microorganisms")
checked <- joins_check_df(x, by)
x_class <- get_prejoined_class(x)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
left_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
# use dplyr if available - it's much faster
dplyr_left <- import_fn("left_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_left)) {
join <- suppressWarnings(
dplyr_left(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
} else {
join <- suppressWarnings(
pm_left_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
}
if (NROW(join) > NROW(x)) {
warning("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
warning_("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
}
class(join) <- x_class
join
@@ -92,17 +123,29 @@ left_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
#' @rdname join
#' @export
right_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
meet_criteria(suffix, allow_class = "character", has_length = 2)
check_dataset_integrity()
check_groups_before_join(x, "right_join_microorganisms")
x <- check_groups_before_join(x, "right_join_microorganisms")
checked <- joins_check_df(x, by)
x_class <- get_prejoined_class(x)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
right_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
# use dplyr if available - it's much faster
dplyr_right <- import_fn("right_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_right)) {
join <- suppressWarnings(
dplyr_right(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
} else {
join <- suppressWarnings(
pm_right_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
}
if (NROW(join) > NROW(x)) {
warning("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
warning_("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
}
class(join) <- x_class
join
@@ -111,17 +154,29 @@ right_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
#' @rdname join
#' @export
full_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
meet_criteria(suffix, allow_class = "character", has_length = 2)
check_dataset_integrity()
check_groups_before_join(x, "full_join_microorganisms")
x <- check_groups_before_join(x, "full_join_microorganisms")
checked <- joins_check_df(x, by)
x_class <- get_prejoined_class(x)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
full_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
# use dplyr if available - it's much faster
dplyr_full <- import_fn("full_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_full)) {
join <- suppressWarnings(
dplyr_full(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
} else {
join <- suppressWarnings(
pm_full_join(x = x, y = microorganisms, by = by, suffix = suffix, ...)
)
}
if (NROW(join) > NROW(x)) {
warning("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
warning_("The newly joined tbl contains ", nrow(join) - nrow(x), " rows more that its original.")
}
class(join) <- x_class
join
@@ -130,15 +185,26 @@ full_join_microorganisms <- function(x, by = NULL, suffix = c("2", ""), ...) {
#' @rdname join
#' @export
semi_join_microorganisms <- function(x, by = NULL, ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
check_dataset_integrity()
check_groups_before_join(x, "semi_join_microorganisms")
x <- check_groups_before_join(x, "semi_join_microorganisms")
x_class <- get_prejoined_class(x)
checked <- joins_check_df(x, by)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
semi_join(x = x, y = microorganisms, by = by, ...)
)
# use dplyr if available - it's much faster
dplyr_semi <- import_fn("semi_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_semi)) {
join <- suppressWarnings(
dplyr_semi(x = x, y = microorganisms, by = by, ...)
)
} else {
join <- suppressWarnings(
pm_semi_join(x = x, y = microorganisms, by = by, ...)
)
}
class(join) <- x_class
join
}
@@ -146,15 +212,26 @@ semi_join_microorganisms <- function(x, by = NULL, ...) {
#' @rdname join
#' @export
anti_join_microorganisms <- function(x, by = NULL, ...) {
meet_criteria(x, allow_class = c("data.frame", "character"))
meet_criteria(by, allow_class = "character", allow_NULL = TRUE)
check_dataset_integrity()
check_groups_before_join(x, "anti_join_microorganisms")
x <- check_groups_before_join(x, "anti_join_microorganisms")
checked <- joins_check_df(x, by)
x_class <- get_prejoined_class(x)
x <- checked$x
by <- checked$by
join <- suppressWarnings(
anti_join(x = x, y = microorganisms, by = by, ...)
)
# use dplyr if available - it's much faster
dplyr_anti <- import_fn("anti_join", "dplyr", error_on_fail = FALSE)
if (!is.null(dplyr_anti)) {
join <- suppressWarnings(
dplyr_anti(x = x, y = microorganisms, by = by, ...)
)
} else {
join <- suppressWarnings(
pm_anti_join(x = x, y = microorganisms, by = by, ...)
)
}
class(join) <- x_class
join
}
@@ -178,7 +255,7 @@ joins_check_df <- function(x, by) {
stop("Cannot join - no column found with name 'mo' or with class <mo>.", call. = FALSE)
}
}
message('Joining, by = "', by, '"') # message same as dplyr::join functions
message_('Joining, by = "', by, '"', add_fn = font_black, as_note = FALSE) # message same as dplyr::join functions
}
if (is.null(names(by))) {
joinby <- colnames(microorganisms)[1]
@@ -200,6 +277,10 @@ get_prejoined_class <- function(x) {
check_groups_before_join <- function(x, fn) {
if (is.data.frame(x) && !is.null(attributes(x)$groups)) {
warning("Groups are dropped, since the ", fn, "() function relies on merge() from base R, not on join() from dplyr.", call. = FALSE)
x <- pm_ungroup(x)
attr(x, "groups") <- NULL
class(x) <- class(x)[!class(x) %like% "group"]
warning_("Groups are dropped, since the ", fn, "() function relies on merge() from base R.", call = FALSE)
}
x
}

View File

@@ -1,37 +1,44 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Key antibiotics for first *weighted* isolates
#' Key Antibiotics for First (Weighted) Isolates
#'
#' These function can be used to determine first isolates (see [first_isolate()]). Using key antibiotics to determine first isolates is more reliable than without key antibiotics. These selected isolates will then be called first *weighted* isolates.
#' @inheritSection lifecycle Stable lifecycle
#' @param x table with antibiotics coloms, like `AMX` or `amox`
#' @param y,z characters to compare
#' These function can be used to determine first isolates (see [first_isolate()]). Using key antibiotics to determine first isolates is more reliable than without key antibiotics. These selected isolates can then be called first 'weighted' isolates.
#' @inheritSection lifecycle Stable Lifecycle
#' @param x a [data.frame] with antibiotics columns, like `AMX` or `amox`. Can be left blank when used inside `dplyr` verbs, such as `filter()`, `mutate()` and `summarise()`.
#' @param y,z character vectors to compare
#' @inheritParams first_isolate
#' @param universal_1,universal_2,universal_3,universal_4,universal_5,universal_6 column names of **broad-spectrum** antibiotics, case-insensitive. At default, the columns containing these antibiotics will be guessed with [guess_ab_col()].
#' @param GramPos_1,GramPos_2,GramPos_3,GramPos_4,GramPos_5,GramPos_6 column names of antibiotics for **Gram-positives**, case-insensitive. At default, the columns containing these antibiotics will be guessed with [guess_ab_col()].
#' @param GramNeg_1,GramNeg_2,GramNeg_3,GramNeg_4,GramNeg_5,GramNeg_6 column names of antibiotics for **Gram-negatives**, case-insensitive. At default, the columns containing these antibiotics will be guessed with [guess_ab_col()].
#' @param warnings give warning about missing antibiotic columns, they will anyway be ignored
#' @param ... other parameters passed on to function
#' @details The function [key_antibiotics()] returns a character vector with 12 antibiotic results for every isolate. These isolates can then be compared using [key_antibiotics_equal()], to check if two isolates have generally the same antibiogram. Missing and invalid values are replaced with a dot (`"."`) by [key_antibiotics()] and ignored by [key_antibiotics_equal()].
#' @param universal_1,universal_2,universal_3,universal_4,universal_5,universal_6 column names of **broad-spectrum** antibiotics, case-insensitive. See details for which antibiotics will be used at default (which are guessed with [guess_ab_col()]).
#' @param GramPos_1,GramPos_2,GramPos_3,GramPos_4,GramPos_5,GramPos_6 column names of antibiotics for **Gram-positives**, case-insensitive. See details for which antibiotics will be used at default (which are guessed with [guess_ab_col()]).
#' @param GramNeg_1,GramNeg_2,GramNeg_3,GramNeg_4,GramNeg_5,GramNeg_6 column names of antibiotics for **Gram-negatives**, case-insensitive. See details for which antibiotics will be used at default (which are guessed with [guess_ab_col()]).
#' @param warnings give a warning about missing antibiotic columns (they will be ignored)
#' @param ... other arguments passed on to functions
#' @details
#' The [key_antibiotics()] function is context-aware when used inside `dplyr` verbs, such as `filter()`, `mutate()` and `summarise()`. This means that then the `x` argument can be left blank, see *Examples*.
#'
#' The function [key_antibiotics()] returns a character vector with 12 antibiotic results for every isolate. These isolates can then be compared using [key_antibiotics_equal()], to check if two isolates have generally the same antibiogram. Missing and invalid values are replaced with a dot (`"."`) by [key_antibiotics()] and ignored by [key_antibiotics_equal()].
#'
#' The [first_isolate()] function only uses this function on the same microbial species from the same patient. Using this, e.g. an MRSA will be included after a susceptible *S. aureus* (MSSA) is found within the same patient episode. Without key antibiotic comparison it would not. See [first_isolate()] for more info.
#'
@@ -64,41 +71,43 @@
#' - Meropenem
#'
#' The function [key_antibiotics_equal()] checks the characters returned by [key_antibiotics()] for equality, and returns a [`logical`] vector.
#' @inheritSection first_isolate Key antibiotics
#' @inheritSection first_isolate Key Antibiotics
#' @rdname key_antibiotics
#' @export
#' @seealso [first_isolate()]
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a dataset available in the AMR package.
#' # See ?example_isolates.
#'
#' \dontrun{
#' library(dplyr)
#' # set key antibiotics to a new variable
#' my_patients <- example_isolates %>%
#' mutate(keyab = key_antibiotics(.)) %>%
#' mutate(
#' # now calculate first isolates
#' first_regular = first_isolate(., col_keyantibiotics = FALSE),
#' # and first WEIGHTED isolates
#' first_weighted = first_isolate(., col_keyantibiotics = "keyab")
#' )
#'
#' # Check the difference, in this data set it results in 7% more isolates:
#' sum(my_patients$first_regular, na.rm = TRUE)
#' sum(my_patients$first_weighted, na.rm = TRUE)
#' }
#'
#' # output of the `key_antibiotics` function could be like this:
#'
#' # output of the `key_antibiotics()` function could be like this:
#' strainA <- "SSSRR.S.R..S"
#' strainB <- "SSSIRSSSRSSS"
#'
#' # those strings can be compared with:
#' key_antibiotics_equal(strainA, strainB)
#' # TRUE, because I is ignored (as well as missing values)
#'
#' key_antibiotics_equal(strainA, strainB, ignore_I = FALSE)
#' # FALSE, because I is not ignored and so the 4th value differs
#' # FALSE, because I is not ignored and so the 4th character differs
#'
#' \donttest{
#' if (require("dplyr")) {
#' # set key antibiotics to a new variable
#' my_patients <- example_isolates %>%
#' mutate(keyab = key_antibiotics()) %>% # no need to define `x`
#' mutate(
#' # now calculate first isolates
#' first_regular = first_isolate(col_keyantibiotics = FALSE),
#' # and first WEIGHTED isolates
#' first_weighted = first_isolate(col_keyantibiotics = "keyab")
#' )
#'
#' # Check the difference, in this data set it results in a lot more isolates:
#' sum(my_patients$first_regular, na.rm = TRUE)
#' sum(my_patients$first_weighted, na.rm = TRUE)
#' }
#' }
key_antibiotics <- function(x,
col_mo = NULL,
universal_1 = guess_ab_col(x, "amoxicillin"),
@@ -121,11 +130,35 @@ key_antibiotics <- function(x,
GramNeg_6 = guess_ab_col(x, "meropenem"),
warnings = TRUE,
...) {
if (missing(x)) {
x <- get_current_data(arg_name = "x", call = -2)
}
meet_criteria(x, allow_class = "data.frame")
meet_criteria(col_mo, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_1, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_2, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_3, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_4, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_5, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(universal_6, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_1, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_2, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_3, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_4, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_5, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramPos_6, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_1, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_2, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_3, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_4, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_5, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(GramNeg_6, allow_class = "character", has_length = 1, allow_NULL = TRUE, allow_NA = TRUE)
meet_criteria(warnings, allow_class = "logical", has_length = 1)
dots <- unlist(list(...))
if (length(dots) != 0) {
# backwards compatibility with old parameters
dots.names <- dots %>% names()
# backwards compatibility with old arguments
dots.names <- dots %pm>% names()
if ("info" %in% dots.names) {
warnings <- dots[which(dots.names == "info")]
}
@@ -135,8 +168,10 @@ key_antibiotics <- function(x,
# -- mo
if (is.null(col_mo)) {
col_mo <- search_type_in_df(x = x, type = "mo")
stop_if(is.null(col_mo), "`col_mo` must be set")
} else {
stop_ifnot(col_mo %in% colnames(x), "column '", col_mo, "' (`col_mo`) not found")
}
stop_if(is.null(col_mo), "`col_mo` must be set")
# check columns
col.list <- c(universal_1, universal_2, universal_3, universal_4, universal_5, universal_6,
@@ -161,11 +196,11 @@ key_antibiotics <- function(x,
}
if (!all(col.list %in% colnames(x))) {
if (warnings == TRUE) {
warning("Some columns do not exist and will be ignored: ",
col.list.bak[!(col.list %in% colnames(x))] %>% toString(),
".\nTHIS MAY STRONGLY INFLUENCE THE OUTCOME.",
immediate. = TRUE,
call. = FALSE)
warning_("Some columns do not exist and will be ignored: ",
col.list.bak[!(col.list %in% colnames(x))] %pm>% toString(),
".\nTHIS MAY STRONGLY INFLUENCE THE OUTCOME.",
immediate = TRUE,
call = FALSE)
}
}
col.list
@@ -200,7 +235,7 @@ key_antibiotics <- function(x,
gram_positive <- gram_positive[!is.null(gram_positive)]
gram_positive <- gram_positive[!is.na(gram_positive)]
if (length(gram_positive) < 12) {
warning("only using ", length(gram_positive), " different antibiotics as key antibiotics for Gram-positives. See ?key_antibiotics.", call. = FALSE)
warning_("Only using ", length(gram_positive), " different antibiotics as key antibiotics for Gram-positives. See ?key_antibiotics.", call = FALSE)
}
gram_negative <- c(universal,
@@ -209,7 +244,7 @@ key_antibiotics <- function(x,
gram_negative <- gram_negative[!is.null(gram_negative)]
gram_negative <- gram_negative[!is.na(gram_negative)]
if (length(gram_negative) < 12) {
warning("only using ", length(gram_negative), " different antibiotics as key antibiotics for Gram-negatives. See ?key_antibiotics.", call. = FALSE)
warning_("Only using ", length(gram_negative), " different antibiotics as key antibiotics for Gram-negatives. See ?key_antibiotics.", call = FALSE)
}
x <- as.data.frame(x, stringsAsFactors = FALSE)
@@ -218,7 +253,7 @@ key_antibiotics <- function(x,
x$key_ab <- NA_character_
# Gram +
x$key_ab <- if_else(x$gramstain == "Gram-positive",
x$key_ab <- pm_if_else(x$gramstain == "Gram-positive",
tryCatch(apply(X = x[, gram_positive],
MARGIN = 1,
FUN = function(x) paste(x, collapse = "")),
@@ -226,7 +261,7 @@ key_antibiotics <- function(x,
x$key_ab)
# Gram -
x$key_ab <- if_else(x$gramstain == "Gram-negative",
x$key_ab <- pm_if_else(x$gramstain == "Gram-negative",
tryCatch(apply(X = x[, gram_negative],
MARGIN = 1,
FUN = function(x) paste(x, collapse = "")),
@@ -236,8 +271,8 @@ key_antibiotics <- function(x,
# format
key_abs <- toupper(gsub("[^SIR]", ".", gsub("(NA|NULL)", ".", x$key_ab)))
if (n_distinct(key_abs) == 1) {
warning("No distinct key antibiotics determined.", call. = FALSE)
if (pm_n_distinct(key_abs) == 1) {
warning_("No distinct key antibiotics determined.", call = FALSE)
}
key_abs
@@ -252,21 +287,27 @@ key_antibiotics_equal <- function(y,
ignore_I = TRUE,
points_threshold = 2,
info = FALSE) {
meet_criteria(y, allow_class = "character")
meet_criteria(z, allow_class = "character")
meet_criteria(type, allow_class = "character", has_length = c(1, 2))
meet_criteria(ignore_I, allow_class = "logical", has_length = 1)
meet_criteria(points_threshold, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(info, allow_class = "logical", has_length = 1)
stop_ifnot(length(y) == length(z), "length of `y` and `z` must be equal")
# y is active row, z is lag
x <- y
y <- z
type <- type[1]
stop_ifnot(length(x) == length(y), "length of `x` and `y` must be equal")
# only show progress bar on points or when at least 5000 isolates
info_needed <- info == TRUE & (type == "points" | length(x) > 5000)
result <- logical(length(x))
if (info_needed == TRUE) {
p <- progress_estimated(length(x))
p <- progress_ticker(length(x))
on.exit(close(p))
}
@@ -315,10 +356,10 @@ key_antibiotics_equal <- function(y,
# - S|R <-> R|S is 1 point
# use the levels of as.rsi (S = 1, I = 2, R = 3)
suppressWarnings(x_split <- x_split %>% as.rsi() %>% as.double())
suppressWarnings(y_split <- y_split %>% as.rsi() %>% as.double())
suppressWarnings(x_split <- x_split %pm>% as.rsi() %pm>% as.double())
suppressWarnings(y_split <- y_split %pm>% as.rsi() %pm>% as.double())
points <- (x_split - y_split) %>% abs() %>% sum(na.rm = TRUE) / 2
points <- (x_split - y_split) %pm>% abs() %pm>% sum(na.rm = TRUE) / 2
result[i] <- points >= points_threshold
} else {

View File

@@ -1,61 +1,75 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Kurtosis of the sample
#' Kurtosis of the Sample
#'
#' @description Kurtosis is a measure of the "tailedness" of the probability distribution of a real-valued random variable.
#' @inheritSection lifecycle Questioning 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.
#' @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!
#' @inheritSection AMR Read more on Our Website!
#' @export
kurtosis <- function(x, na.rm = FALSE) {
kurtosis <- function(x, na.rm = FALSE, excess = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
meet_criteria(excess, allow_class = "logical", has_length = 1)
UseMethod("kurtosis")
}
#' @method kurtosis default
#' @rdname kurtosis
#' @export
kurtosis.default <- function(x, na.rm = FALSE) {
kurtosis.default <- function(x, na.rm = FALSE, excess = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
meet_criteria(excess, allow_class = "logical", has_length = 1)
x <- as.vector(x)
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
n <- length(x)
n * base::sum((x - base::mean(x, na.rm = na.rm))^4, na.rm = na.rm) /
(base::sum((x - base::mean(x, na.rm = na.rm))^2, na.rm = na.rm)^2)
k <- n * sum((x - mean(x, na.rm = na.rm))^4, na.rm = na.rm) /
(sum((x - mean(x, na.rm = na.rm))^2, na.rm = na.rm)^2)
k - ifelse(excess, 3, 0)
}
#' @method kurtosis matrix
#' @rdname kurtosis
#' @export
kurtosis.matrix <- function(x, na.rm = FALSE) {
base::apply(x, 2, kurtosis.default, na.rm = na.rm)
kurtosis.matrix <- function(x, na.rm = FALSE, excess = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
meet_criteria(excess, allow_class = "logical", has_length = 1)
apply(x, 2, kurtosis.default, na.rm = na.rm, excess = excess)
}
#' @method kurtosis data.frame
#' @rdname kurtosis
#' @export
kurtosis.data.frame <- function(x, na.rm = FALSE) {
base::sapply(x, kurtosis.default, na.rm = na.rm)
kurtosis.data.frame <- function(x, na.rm = FALSE, excess = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
meet_criteria(excess, allow_class = "logical", has_length = 1)
vapply(FUN.VALUE = double(1), x, kurtosis.default, na.rm = na.rm, excess = excess)
}

View File

@@ -1,50 +1,54 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR 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
#' 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://www.Tidyverse.org/lifecycle).
#'
#' \if{html}{\figure{lifecycle_Tidyverse.svg}{options: height=200px style=margin-bottom:5px} \cr}
#' \if{html}{\figure{lifecycle_tidyverse.svg}{options: height=200px style=margin-bottom:5px} \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:
#' @section Experimental Lifecycle:
#' \if{html}{\figure{lifecycle_experimental.svg}{options: style=margin-bottom:5px} \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:
#' @section Maturing Lifecycle:
#' \if{html}{\figure{lifecycle_maturing.svg}{options: style=margin-bottom:5px} \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:
#' @section Stable Lifecycle:
#' \if{html}{\figure{lifecycle_stable.svg}{options: style=margin-bottom:5px} \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, a parameter will be deprecated and first continue to work, but will emit an 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 the unlying code needs breaking changes, they will occur gradually. For example, a argument will be deprecated and first continue to work, but will emit an 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:5px} \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:
#' @section Questioning Lifecycle:
#' \if{html}{\figure{lifecycle_questioning.svg}{options: style=margin-bottom:5px} \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

View File

@@ -1,30 +1,34 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Pattern Matching
#' Pattern Matching with Keyboard Shortcut
#'
#' Convenient wrapper around [grep()] 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
#' @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 string containing a regular expression (or [`character`] string for `fixed = TRUE`) to be matched in the given character vector. Coerced by [as.character()] to a character string if possible. If a [`character`] vector of length 2 or more is supplied, the first element is used with a warning.
#' @param pattern a character string containing a regular expression (or [character] string for `fixed = TRUE`) to be matched in the given character vector. Coerced by [as.character()] to a character string if possible. If a [character] vector of length 2 or more is supplied, the first element is used with a warning.
#' @param ignore.case if `FALSE`, the pattern matching is *case sensitive* and if `TRUE`, case is ignored during matching.
#' @return A [`logical`] vector
#' @name like
@@ -32,15 +36,15 @@
#' @export
#' @details
#' The `%like%` function:
#' * Is case insensitive (use `%like_case%` for case-sensitive matching)
#' * Is case-insensitive (use `%like_case%` for case-sensitive matching)
#' * Supports multiple patterns
#' * Checks if `pattern` is a regular expression and sets `fixed = TRUE` if not, to greatly improve speed
#' * Tries again with `perl = TRUE` if regex fails
#'
#' Using RStudio? This function can also be inserted from the Addins menu and can have its own Keyboard Shortcut like `Ctrl+Shift+L` or `Cmd+Shift+L` (see `Tools` > `Modify Keyboard Shortcuts...`).
#' Using RStudio? The text `%like%` can also be directly inserted in your code from the Addins menu and can have its own Keyboard Shortcut like `Ctrl+Shift+L` or `Cmd+Shift+L` (see `Tools` > `Modify Keyboard Shortcuts...`).
#' @source Idea from the [`like` function from the `data.table` package](https://github.com/Rdatatable/data.table/blob/master/R/like.R)
#' @seealso [base::grep()]
#' @inheritSection AMR Read more on our website!
#' @seealso [grep()]
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # simple test
#' a <- "This is a test"
@@ -57,27 +61,48 @@
#' #> TRUE TRUE TRUE
#'
#' # get isolates whose name start with 'Ent' or 'ent'
#' \dontrun{
#' library(dplyr)
#' example_isolates %>%
#' filter(mo_name(mo) %like% "^ent")
#' \donttest{
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter(mo_name(mo) %like% "^ent")
#' }
#' }
like <- function(x, pattern, ignore.case = TRUE) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(pattern, allow_NA = FALSE)
meet_criteria(ignore.case, allow_class = "logical", has_length = 1)
# set to fixed if no regex found
fixed <- all(!grepl("[\\[$.^*?+-}{|)(]", pattern))
fixed <- !any(is_possibly_regex(pattern))
if (ignore.case == TRUE) {
# set here, otherwise if fixed = TRUE, this warning will be thrown: argument 'ignore.case = TRUE' will be ignored
# set here, otherwise if fixed = TRUE, this warning will be thrown: argument `ignore.case = TRUE` will be ignored
x <- tolower(x)
pattern <- tolower(pattern)
}
if (length(pattern) > 1 & length(x) == 1) {
x <- rep(x, length(pattern))
}
if (all(is.na(x))) {
return(rep(FALSE, length(x)))
}
if (length(pattern) > 1) {
res <- vector(length = length(pattern))
if (length(x) != length(pattern)) {
if (length(x) == 1) {
x <- rep(x, length(pattern))
}
# return TRUE for every 'x' that matches any 'pattern', FALSE otherwise
res <- sapply(pattern, function(pttrn) base::grepl(pttrn, x, ignore.case = FALSE, fixed = fixed))
for (i in seq_len(length(res))) {
if (is.factor(x[i])) {
res[i] <- as.integer(x[i]) %in% grep(pattern[i], levels(x[i]), ignore.case = FALSE, fixed = fixed)
} else {
res[i] <- grepl(pattern[i], x[i], ignore.case = FALSE, fixed = fixed)
}
}
res <- vapply(FUN.VALUE = logical(1), pattern, function(pttrn) grepl(pttrn, x, ignore.case = FALSE, fixed = fixed))
res2 <- as.logical(rowSums(res))
# get only first item of every hit in pattern
res2[duplicated(res)] <- FALSE
@@ -85,12 +110,11 @@ like <- function(x, pattern, ignore.case = TRUE) {
return(res2)
} else {
# x and pattern are of same length, so items with each other
res <- vector(length = length(pattern))
for (i in seq_len(length(res))) {
if (is.factor(x[i])) {
res[i] <- as.integer(x[i]) %in% base::grep(pattern[i], levels(x[i]), ignore.case = FALSE, fixed = fixed)
res[i] <- as.integer(x[i]) %in% grep(pattern[i], levels(x[i]), ignore.case = FALSE, fixed = fixed)
} else {
res[i] <- base::grepl(pattern[i], x[i], ignore.case = FALSE, fixed = fixed)
res[i] <- grepl(pattern[i], x[i], ignore.case = FALSE, fixed = fixed)
}
}
return(res)
@@ -99,13 +123,13 @@ like <- function(x, pattern, ignore.case = TRUE) {
# the regular way how grepl works; just one pattern against one or more x
if (is.factor(x)) {
as.integer(x) %in% base::grep(pattern, levels(x), ignore.case = FALSE, fixed = fixed)
as.integer(x) %in% grep(pattern, levels(x), ignore.case = FALSE, fixed = fixed)
} else {
tryCatch(base::grepl(pattern, x, ignore.case = FALSE, fixed = fixed),
tryCatch(grepl(pattern, x, ignore.case = FALSE, fixed = fixed),
error = function(e) {
if (grepl("invalid reg(ular )?exp", e$message, ignore.case = TRUE)) {
# try with perl = TRUE:
return(base::grepl(pattern = pattern,
return(grepl(pattern = pattern,
x = x,
ignore.case = FALSE,
fixed = fixed,
@@ -121,11 +145,27 @@ like <- function(x, pattern, ignore.case = TRUE) {
#' @rdname like
#' @export
"%like%" <- function(x, pattern) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(pattern, allow_NA = FALSE)
like(x, pattern, ignore.case = TRUE)
}
#' @rdname like
#' @export
"%like_case%" <- function(x, pattern) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(pattern, allow_NA = FALSE)
like(x, pattern, ignore.case = FALSE)
}
"%like_perl%" <- function(x, pattern) {
meet_criteria(x, allow_NA = TRUE)
meet_criteria(pattern, allow_NA = FALSE)
# convenient for e.g. matching all Klebsiella and Raoultella, but not
# K. aerogenes: fullname %like_perl% "^(Klebsiella(?! aerogenes)|Raoultella)"
grepl(x = tolower(x),
pattern = tolower(pattern),
perl = TRUE,
fixed = FALSE,
ignore.case = TRUE)
}

831
R/mdro.R

File diff suppressed because it is too large Load Diff

149
R/mic.R
View File

@@ -1,37 +1,41 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Class 'mic'
#' Transform Input to Minimum Inhibitory Concentrations (MIC)
#'
#' This transforms a vector to a new class [`mic`], which is an ordered [`factor`] with valid MIC values as levels. Invalid MIC values will be translated as `NA` with a warning.
#' @inheritSection lifecycle Stable lifecycle
#' This transforms a vector to a new class [`mic`], which is an ordered [factor] with valid minimum inhibitory concentrations (MIC) as levels. Invalid MIC values will be translated as `NA` with a warning.
#' @inheritSection lifecycle Stable Lifecycle
#' @rdname as.mic
#' @param x 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.
#' @return Ordered [`factor`] with new class [`mic`]
#' @return Ordered [factor] with additional class [`mic`]
#' @aliases mic
#' @export
#' @seealso [as.rsi()]
#' @inheritSection AMR Read more on our website!
#' @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"))
#' is.mic(mic_data)
@@ -52,10 +56,13 @@
#' plot(mic_data)
#' barplot(mic_data)
as.mic <- function(x, na.rm = FALSE) {
meet_criteria(x, allow_class = c("mic", "character", "numeric", "integer"), allow_NA = TRUE)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
if (is.mic(x)) {
x
} else {
x <- x %>% unlist()
x <- x %pm>% unlist()
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
@@ -100,39 +107,42 @@ as.mic <- function(x, na.rm = FALSE) {
# these are allowed MIC values and will become factor levels
ops <- c("<", "<=", "", ">=", ">")
lvls <- c(c(t(sapply(ops, function(x) paste0(x, "0.00", 1:9)))),
unique(c(t(sapply(ops, function(x) paste0(x, sort(as.double(paste0("0.0",
lvls <- 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(sapply(ops, function(x) paste0(x, sort(as.double(paste0("0.",
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(sapply(ops, function(x) paste0(x, sort(c(1:9, 1.5)))))),
c(t(sapply(ops, function(x) paste0(x, c(10:98)[9:98 %% 2 == TRUE])))),
c(t(sapply(ops, function(x) paste0(x, sort(c(2 ^ c(7:10), 80 * c(2:12))))))))
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(15), ops, function(x) paste0(x, sort(c(2 ^ c(7:10), 80 * c(2:12))))))))
na_before <- x[is.na(x) | x == ""] %>% length()
na_before <- x[is.na(x) | x == ""] %pm>% length()
x[!x %in% lvls] <- NA
na_after <- x[is.na(x) | x == ""] %>% length()
na_after <- x[is.na(x) | x == ""] %pm>% length()
if (na_before != na_after) {
list_missing <- x.bak[is.na(x) & !is.na(x.bak) & x.bak != ""] %>%
unique() %>%
list_missing <- x.bak[is.na(x) & !is.na(x.bak) & x.bak != ""] %pm>%
unique() %pm>%
sort()
list_missing <- paste0('"', list_missing, '"', collapse = ", ")
warning(na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid MICs: ",
list_missing, call. = FALSE)
warning_(na_after - na_before, " results truncated (",
round(((na_after - na_before) / length(x)) * 100),
"%) that were invalid MICs: ",
list_missing, call = FALSE)
}
structure(.Data = factor(x, levels = lvls, ordered = TRUE),
class = c("mic", "ordered", "factor"))
set_clean_class(factor(x, levels = lvls, ordered = TRUE),
new_class = c("mic", "ordered", "factor"))
}
}
all_valid_mics <- function(x) {
if (!inherits(x, c("mic", "character", "factor", "numeric", "integer"))) {
return(FALSE)
}
x_mic <- tryCatch(suppressWarnings(as.mic(x[!is.na(x)])),
error = function(e) NA)
!any(is.na(x_mic)) & !all(is.na(x))
!any(is.na(x_mic)) && !all(is.na(x))
}
#' @rdname as.mic
@@ -145,32 +155,48 @@ is.mic <- function(x) {
#' @export
#' @noRd
as.double.mic <- function(x, ...) {
as.double(gsub("(<|=|>)+", "", as.character(x)))
as.double(gsub("[<=>]+", "", as.character(x)))
}
#' @method as.integer mic
#' @export
#' @noRd
as.integer.mic <- function(x, ...) {
as.integer(gsub("(<|=|>)+", "", as.character(x)))
as.integer(gsub("[<=>]+", "", as.character(x)))
}
#' @method as.numeric mic
#' @export
#' @noRd
as.numeric.mic <- function(x, ...) {
as.numeric(gsub("(<|=|>)+", "", as.character(x)))
as.numeric(gsub("[<=>]+", "", as.character(x)))
}
#' @method droplevels mic
#' @export
#' @noRd
droplevels.mic <- function(x, exclude = ifelse(anyNA(levels(x)), NULL, NA), ...) {
droplevels.mic <- function(x, exclude = if (any(is.na(levels(x)))) NULL else NA, ...) {
x <- droplevels.factor(x, exclude = exclude, ...)
class(x) <- c("mic", "ordered", "factor")
x
}
# will be exported using s3_register() in R/zzz.R
pillar_shaft.mic <- function(x, ...) {
crude_numbers <- as.double(x)
operators <- gsub("[^<=>]+", "", as.character(x))
pasted <- trimws(paste0(operators, trimws(format(crude_numbers))))
out <- pasted
out[is.na(x)] <- font_na(NA)
out <- gsub("(<|=|>)", font_silver("\\1"), out)
create_pillar_column(out, align = "right", width = max(nchar(pasted)))
}
# will be exported using s3_register() in R/zzz.R
type_sum.mic <- function(x, ...) {
"mic"
}
#' @method print mic
#' @export
#' @noRd
@@ -184,53 +210,63 @@ print.mic <- function(x, ...) {
#' @noRd
summary.mic <- function(object, ...) {
x <- object
n_total <- x %>% length()
n_total <- length(x)
x <- x[!is.na(x)]
n <- x %>% length()
c(
"Class" = "mic",
"<NA>" = n_total - n,
"Min." = sort(x)[1] %>% as.character(),
"Max." = sort(x)[n] %>% as.character()
)
n <- length(x)
value <- c("Class" = "mic",
"<NA>" = n_total - n,
"Min." = as.character(sort(x)[1]),
"Max." = as.character(sort(x)[n]))
class(value) <- c("summaryDefault", "table")
value
}
#' @method plot mic
#' @export
#' @importFrom graphics barplot axis par
#' @noRd
#' @importFrom graphics barplot axis
#' @rdname plot
plot.mic <- function(x,
main = paste("MIC values of", deparse(substitute(x))),
ylab = "Frequency",
xlab = "MIC value",
axes = FALSE,
...) {
barplot(table(droplevels.factor(x)),
meet_criteria(main, allow_class = "character", has_length = 1)
meet_criteria(ylab, allow_class = "character", has_length = 1)
meet_criteria(xlab, allow_class = "character", has_length = 1)
meet_criteria(axes, allow_class = "logical", has_length = 1)
barplot(table(as.double(x)),
ylab = ylab,
xlab = xlab,
axes = axes,
main = main,
...)
axis(2, seq(0, max(table(droplevels.factor(x)))))
axis(2, seq(0, max(table(as.double(x)))))
}
#' @method barplot mic
#' @export
#' @importFrom graphics barplot axis
#' @noRd
#' @rdname plot
barplot.mic <- function(height,
main = paste("MIC values of", deparse(substitute(height))),
ylab = "Frequency",
xlab = "MIC value",
axes = FALSE,
...) {
barplot(table(droplevels.factor(height)),
meet_criteria(main, allow_class = "character", has_length = 1)
meet_criteria(ylab, allow_class = "character", has_length = 1)
meet_criteria(xlab, allow_class = "character", has_length = 1)
meet_criteria(axes, allow_class = "logical", has_length = 1)
barplot(table(as.double(height)),
ylab = ylab,
xlab = xlab,
axes = axes,
main = main,
...)
axis(2, seq(0, max(table(droplevels.factor(height)))))
axis(2, seq(0, max(table(as.double(height)))))
}
#' @method [ mic
@@ -271,7 +307,28 @@ barplot.mic <- function(height,
#' @export
#' @noRd
c.mic <- function(x, ...) {
y <- unlist(lapply(list(...), as.character))
x <- as.character(x)
as.mic(c(x, y))
}
#' @method unique mic
#' @export
#' @noRd
unique.mic <- function(x, incomparables = FALSE, ...) {
y <- NextMethod()
attributes(y) <- attributes(x)
y
}
# will be exported using s3_register() in R/zzz.R
get_skimmers.mic <- function(column) {
skimr::sfl(
skim_type = "mic",
min = ~as.character(sort(stats::na.omit(.))[1]),
max = ~as.character(sort(stats::na.omit(.))[length(stats::na.omit(.))]),
median = ~as.character(stats::na.omit(.)[as.double(stats::na.omit(.)) == median(as.double(stats::na.omit(.)))])[1],
n_unique = ~pm_n_distinct(., na.rm = TRUE),
hist_log2 = ~skimr::inline_hist(log2(as.double(stats::na.omit(.))))
)
}

1423
R/mo.R

File diff suppressed because it is too large Load Diff

94
R/mo_matching_score.R Executable file
View File

@@ -0,0 +1,94 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Calculate the Matching Score for Microorganisms
#'
#' This algorithm is used by [as.mo()] and all the [`mo_*`][mo_property()] functions to determine the most probable match of taxonomic records based on user input.
#' @inheritSection lifecycle Stable Lifecycle
#' @author Matthijs S. 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:
#' With ambiguous user input in [as.mo()] and all the [`mo_*`][mo_property()] functions, the returned results are chosen based on their matching score using [mo_matching_score()]. This matching score \eqn{m}, is calculated as:
#'
#' \ifelse{latex}{\deqn{m_{(x, n)} = \frac{l_{n} - 0.5 \cdot \min \begin{cases}l_{n} \\ \textrm{lev}(x, n)\end{cases}}{l_{n} \cdot p_{n} \cdot k_{n}}}}{\ifelse{html}{\figure{mo_matching_score.png}{options: width="300px" alt="mo matching score"}}{m(x, n) = ( l_n * min(l_n, lev(x, n) ) ) / ( l_n * p_n * k_n )}}
#'
#' where:
#'
#' * \ifelse{html}{\out{<i>x</i> is the user input;}}{\eqn{x} is the user input;}
#' * \ifelse{html}{\out{<i>n</i> is a taxonomic name (genus, species, and subspecies);}}{\eqn{n} is a taxonomic name (genus, species, and subspecies);}
#' * \ifelse{html}{\out{<i>l<sub>n</sub></i> is the length of <i>n</i>;}}{l_n is the length of \eqn{n};}
#' * \ifelse{html}{\out{<i>lev</i> is the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance function</a>, which counts any insertion, deletion and substitution as 1 that is needed to change <i>x</i> into <i>n</i>;}}{lev is the Levenshtein distance function, which counts any insertion, deletion and substitution as 1 that is needed to change \eqn{x} into \eqn{n};}
#' * \ifelse{html}{\out{<i>p<sub>n</sub></i> is the human pathogenic prevalence group of <i>n</i>, as described below;}}{p_n is the human pathogenic prevalence group of \eqn{n}, as described below;}
#' * \ifelse{html}{\out{<i>k<sub>n</sub></i> is the taxonomic kingdom of <i>n</i>, set as Bacteria = 1, Fungi = 2, Protozoa = 3, Archaea = 4, others = 5.}}{l_n is the taxonomic kingdom of \eqn{n}, set as Bacteria = 1, Fungi = 2, Protozoa = 3, Archaea = 4, others = 5.}
#'
#' The grouping into human pathogenic prevalence (\eqn{p}) is based on experience from several microbiological laboratories in the Netherlands in conjunction with international reports on pathogen prevalence. **Group 1** (most prevalent microorganisms) consists of all microorganisms where the taxonomic class is Gammaproteobacteria or where the taxonomic genus is *Enterococcus*, *Staphylococcus* or *Streptococcus*. This group consequently contains all common Gram-negative bacteria, such as *Pseudomonas* and *Legionella* and all species within the order Enterobacterales. **Group 2** consists of all microorganisms where the taxonomic phylum is Proteobacteria, Firmicutes, Actinobacteria or Sarcomastigophora, or where the taxonomic genus is *Absidia*, *Acremonium*, *Actinotignum*, *Alternaria*, *Anaerosalibacter*, *Apophysomyces*, *Arachnia*, *Aspergillus*, *Aureobacterium*, *Aureobasidium*, *Bacteroides*, *Basidiobolus*, *Beauveria*, *Blastocystis*, *Branhamella*, *Calymmatobacterium*, *Candida*, *Capnocytophaga*, *Catabacter*, *Chaetomium*, *Chryseobacterium*, *Chryseomonas*, *Chrysonilia*, *Cladophialophora*, *Cladosporium*, *Conidiobolus*, *Cryptococcus*, *Curvularia*, *Exophiala*, *Exserohilum*, *Flavobacterium*, *Fonsecaea*, *Fusarium*, *Fusobacterium*, *Hendersonula*, *Hypomyces*, *Koserella*, *Lelliottia*, *Leptosphaeria*, *Leptotrichia*, *Malassezia*, *Malbranchea*, *Mortierella*, *Mucor*, *Mycocentrospora*, *Mycoplasma*, *Nectria*, *Ochroconis*, *Oidiodendron*, *Phoma*, *Piedraia*, *Pithomyces*, *Pityrosporum*, *Prevotella*,\\*Pseudallescheria*, *Rhizomucor*, *Rhizopus*, *Rhodotorula*, *Scolecobasidium*, *Scopulariopsis*, *Scytalidium*,*Sporobolomyces*, *Stachybotrys*, *Stomatococcus*, *Treponema*, *Trichoderma*, *Trichophyton*, *Trichosporon*, *Tritirachium* or *Ureaplasma*. **Group 3** consists of all other microorganisms.
#'
#' All matches are sorted descending on their matching score and for all user input values, the top match will be returned. This will lead to the effect that e.g., `"E. coli"` will return the microbial ID of *Escherichia coli* (\eqn{m = `r round(mo_matching_score("E. coli", "Escherichia coli"), 3)`}, a highly prevalent microorganism found in humans) and not *Entamoeba coli* (\eqn{m = `r round(mo_matching_score("E. coli", "Entamoeba coli"), 3)`}, a less prevalent microorganism in humans), although the latter would alphabetically come first.
#' @export
#' @inheritSection AMR Reference Data Publicly Available
#' @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 <- function(x, n) {
meet_criteria(x, allow_class = c("character", "data.frame", "list"))
meet_criteria(n, allow_class = "character")
x <- parse_and_convert(x)
# no dots and other non-whitespace characters
x <- gsub("[^a-zA-Z0-9 \\(\\)]+", "", x)
# only keep one space
x <- gsub(" +", " ", x)
# n is always a taxonomically valid full name
if (length(n) == 1) {
n <- rep(n, length(x))
}
if (length(x) == 1) {
x <- rep(x, length(n))
}
# length of fullname
l_n <- nchar(n)
lev <- double(length = length(x))
l_n.lev <- double(length = length(x))
for (i in seq_len(length(x))) {
# determine Levenshtein distance, but maximise to nchar of n
lev[i] <- utils::adist(x[i], n[i], ignore.case = FALSE, fixed = TRUE)
# minimum of (l_n, Levenshtein distance)
l_n.lev[i] <- min(l_n[i], as.double(lev[i]))
}
# human pathogenic prevalence (1 to 3), see ?as.mo
p_n <- MO_lookup[match(n, MO_lookup$fullname), "prevalence", drop = TRUE]
# kingdom index (Bacteria = 1, Fungi = 2, Protozoa = 3, Archaea = 4, others = 5)
k_n <- MO_lookup[match(n, MO_lookup$fullname), "kingdom_index", drop = TRUE]
# matching score:
(l_n - 0.5 * l_n.lev) / (l_n * p_n * k_n)
}

View File

@@ -1,60 +1,71 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Property of a microorganism
#' Get Properties of a Microorganism
#'
#' Use these functions to return a specific property of a microorganism. All input values will be evaluated internally with [as.mo()], which makes it possible to use microbial abbreviations, codes and names as input. Please see *Examples*.
#' @inheritSection lifecycle Stable lifecycle
#' @param x any (vector of) text that can be coerced to a valid microorganism code with [as.mo()]
#' @param property one of the column names of the [microorganisms] data set or `"shortname"`
#' @param language language of the returned text, defaults to system language (see [get_locale()]) and can also be set with `getOption("AMR_locale")`. Use `language = NULL` or `language = ""` to prevent translation.
#' @param ... other parameters passed on to [as.mo()]
#' @param open browse the URL using [utils::browseURL()]
#' 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 paste0('"``', colnames(microorganisms), '\``"', collapse = ", ")`, or must be `"shortname"`
#' @param language language of the returned text, defaults to system language (see [get_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.
#' @param ... other arguments passed on to [as.mo()], such as 'allow_uncertain' and 'ignore_pattern'
#' @param ab any (vector of) text that can be coerced to a valid antibiotic code with [as.ab()]
#' @param open browse the URL using [`browseURL()`][utils::browseURL()]
#' @details All functions will return the most recently known taxonomic property according to the Catalogue of Life, except for [mo_ref()], [mo_authors()] and [mo_year()]. Please refer to this example, knowing that *Escherichia blattae* was renamed to *Shimwellia blattae* in 2010:
#' - `mo_name("Escherichia blattae")` will return `"Shimwellia blattae"` (with a message about the renaming)
#' - `mo_ref("Escherichia blattae")` will return `"Burgess et al., 1973"` (with a message about the renaming)
#' - `mo_ref("Shimwellia blattae")` will return `"Priest et al., 2010"` (without a message)
#'
#' The short name - [mo_shortname()] - almost always returns the first character of the genus and the full species, like `"E. coli"`. Exceptions are abbreviations of staphylococci (like *"CoNS"*, Coagulase-Negative Staphylococci) and beta-haemolytic streptococci (like *"GBS"*, Group B Streptococci). Please bear in mind that e.g. *E. coli* could mean *Escherichia coli* (kingdom of Bacteria) as well as *Entamoeba coli* (kingdom of Protozoa). Returning to the full name will be done using [as.mo()] internally, giving priority to bacteria and human pathogens, i.e. `"E. coli"` will be considered *Escherichia coli*. In other words, `mo_fullname(mo_shortname("Entamoeba coli"))` returns `"Escherichia coli"`.
#'
#' The short name - [mo_shortname()] - almost always returns the first character of the genus and the full species, like `"E. coli"`. Exceptions are abbreviations of staphylococci (such as *"CoNS"*, Coagulase-Negative Staphylococci) and beta-haemolytic streptococci (such as *"GBS"*, Group B Streptococci). Please bear in mind that e.g. *E. coli* could mean *Escherichia coli* (kingdom of Bacteria) as well as *Entamoeba coli* (kingdom of Protozoa). Returning to the full name will be done using [as.mo()] internally, giving priority to bacteria and human pathogens, i.e. `"E. coli"` will be considered *Escherichia coli*. In other words, `mo_fullname(mo_shortname("Entamoeba coli"))` returns `"Escherichia coli"`.
#'
#' Since the top-level of the taxonomy is sometimes referred to as 'kingdom' and sometimes as 'domain', the functions [mo_kingdom()] and [mo_domain()] return the exact same results.
#'
#' The Gram stain - [mo_gramstain()] - will be determined based on the taxonomic kingdom and phylum. According to Cavalier-Smith (2002, [PMID 11837318](https://pubmed.ncbi.nlm.nih.gov/11837318)), who defined subkingdoms Negibacteria and Posibacteria, only these phyla are Posibacteria: Actinobacteria, Chloroflexi, Firmicutes and Tenericutes. These bacteria are considered Gram-positive - all other bacteria are considered Gram-negative. Species outside the kingdom of Bacteria will return a value `NA`.
#' The Gram stain - [mo_gramstain()] - will be determined based on the taxonomic kingdom and phylum. According to Cavalier-Smith (2002, [PMID 11837318](https://pubmed.ncbi.nlm.nih.gov/11837318)), who defined subkingdoms Negibacteria and Posibacteria, only these phyla are Posibacteria: Actinobacteria, Chloroflexi, Firmicutes and Tenericutes. These bacteria are considered Gram-positive - all other bacteria are considered Gram-negative. Species outside the kingdom of Bacteria will return a value `NA`. Functions [mo_is_gram_negative()] and [mo_is_gram_positive()] always return `TRUE` or `FALSE` (except when the input is `NA` or the MO code is `UNKNOWN`), thus always return `FALSE` for species outside the taxonomic kingdom of Bacteria.
#'
#' Determination of yeasts - [mo_is_yeast()] - will be based on the taxonomic phylum, class and order. Budding yeasts are true fungi of the phylum Ascomycetes, class Saccharomycetes (also called Hemiascomycetes). The true yeasts are separated into one main order Saccharomycetales. For all microorganisms that are in one of those two groups, the function will return `TRUE`. It returns `FALSE` for all other taxonomic entries.
#'
#' Intrinsic resistance - [mo_is_intrinsic_resistant()] - will be determined based on the [intrinsic_resistant] data set, which is based on `r format_eucast_version_nr(3.2)`. The [mo_is_intrinsic_resistant()] can be vectorised over arguments `x` (input for microorganisms) and over `ab` (input for antibiotics).
#'
#' All output will be [translate]d where possible.
#'
#' The function [mo_url()] will return the direct URL to the online database entry, which also shows the scientific reference of the concerned species.
#' @inheritSection mo_matching_score Matching Score for Microorganisms
#' @inheritSection catalogue_of_life Catalogue of Life
#' @inheritSection as.mo Source
#' @rdname mo_property
#' @name mo_property
#' @return
#' - An [`integer`] in case of [mo_year()]
#' - A [`list`] in case of [mo_taxonomy()] and [mo_info()]
#' - A named [`character`] in case of [mo_url()]
#' - A [`double`] in case of [mo_snomed()]
#' - A [`character`] in all other cases
#' - An [integer] in case of [mo_year()]
#' - A [list] in case of [mo_taxonomy()] and [mo_info()]
#' - A named [character] in case of [mo_url()]
#' - A [double] in case of [mo_snomed()]
#' - A [character] in all other cases
#' @export
#' @seealso [microorganisms]
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Reference Data Publicly Available
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # taxonomic tree -----------------------------------------------------------
#' mo_kingdom("E. coli") # "Bacteria"
@@ -116,7 +127,7 @@
#' mo_shortname("S. pyo", Lancefield = TRUE) # "GAS" (='Group A Streptococci')
#'
#'
#' # language support for German, Dutch, Spanish, Portuguese, Italian and French
#' # 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"
@@ -134,13 +145,34 @@
#' language = "nl") # "Streptococcus groep A"
#'
#'
#' # other --------------------------------------------------------------------
#'
#' mo_is_yeast(c("Candida", "E. coli")) # TRUE, FALSE
#'
#' # gram stains and intrinsic resistance can also be used as a filter in dplyr verbs
#' if (require("dplyr")) {
#' example_isolates %>%
#' filter(mo_is_gram_positive())
#'
#' example_isolates %>%
#' filter(mo_is_intrinsic_resistant(ab = "vanco"))
#' }
#'
#'
#' # get a list with the complete taxonomy (from kingdom to subspecies)
#' mo_taxonomy("E. coli")
#' # get a list with the taxonomy, the authors, Gram-stain and URL to the online database
#' mo_info("E. coli")
#' }
mo_name <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "fullname", ...), language = language, only_unknown = FALSE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_name")
}
meet_criteria(x, allow_NA = TRUE)
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, ...), language = language, only_unknown = FALSE)
}
#' @rdname mo_property
@@ -150,7 +182,14 @@ mo_fullname <- mo_name
#' @rdname mo_property
#' @export
mo_shortname <- function(x, language = get_locale(), ...) {
x.mo <- as.mo(x, ...)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_shortname")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x.mo <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
@@ -160,14 +199,20 @@ mo_shortname <- function(x, language = get_locale(), ...) {
}
# get first char of genus and complete species in English
shortnames <- paste0(substr(mo_genus(x.mo, language = NULL), 1, 1), ". ", replace_empty(mo_species(x.mo, language = NULL)))
genera <- mo_genus(x.mo, language = NULL)
shortnames <- paste0(substr(genera, 1, 1), ". ", replace_empty(mo_species(x.mo, language = NULL)))
# exceptions for Staphylococci
# exceptions for where no species is known
shortnames[shortnames %like% ".[.] spp[.]"] <- genera[shortnames %like% ".[.] spp[.]"]
# exceptions for staphylococci
shortnames[shortnames == "S. coagulase-negative"] <- "CoNS"
shortnames[shortnames == "S. coagulase-positive"] <- "CoPS"
# exceptions for Streptococci: Streptococcus Group A -> GAS
# exceptions for streptococci: Group A Streptococcus -> GAS
shortnames[shortnames %like% "S. group [ABCDFGHK]"] <- paste0("G", gsub("S. group ([ABCDFGHK])", "\\1", shortnames[shortnames %like% "S. group [ABCDFGHK]"]), "S")
# unknown species etc.
shortnames[shortnames %like% "unknown"] <- paste0("(", trimws(gsub("[^a-zA-Z -]", "", shortnames[shortnames %like% "unknown"])), ")")
shortnames[is.na(x.mo)] <- NA_character_
load_mo_failures_uncertainties_renamed(metadata)
translate_AMR(shortnames, language = language, only_unknown = FALSE)
}
@@ -175,49 +220,105 @@ mo_shortname <- function(x, language = get_locale(), ...) {
#' @rdname mo_property
#' @export
mo_subspecies <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "subspecies", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_subspecies")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_species <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "species", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_species")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_genus <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "genus", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_genus")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_family <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "family", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_family")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_order <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "order", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_order")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_class <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "class", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_class")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_phylum <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "phylum", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_phylum")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_kingdom <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "kingdom", ...), language = language, only_unknown = TRUE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_kingdom")
}
meet_criteria(x, allow_NA = TRUE)
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)
}
#' @rdname mo_property
@@ -227,13 +328,30 @@ mo_domain <- mo_kingdom
#' @rdname mo_property
#' @export
mo_type <- function(x, language = get_locale(), ...) {
translate_AMR(mo_validate(x = x, property = "kingdom", ...), language = language, only_unknown = FALSE)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_type")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
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)
}
#' @rdname mo_property
#' @export
mo_gramstain <- function(x, language = get_locale(), ...) {
x.mo <- as.mo(x, ...)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_gramstain")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x.mo <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
x.phylum <- mo_phylum(x.mo)
@@ -263,20 +381,141 @@ mo_gramstain <- function(x, language = get_locale(), ...) {
#' @rdname mo_property
#' @export
mo_snomed <- function(x, ...) {
mo_validate(x = x, property = "snomed", ...)
mo_is_gram_negative <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_is_gram_negative")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x.mo <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
grams <- mo_gramstain(x.mo, language = NULL)
load_mo_failures_uncertainties_renamed(metadata)
out <- grams == "Gram-negative" & !is.na(grams)
out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA
out
}
#' @rdname mo_property
#' @export
mo_ref <- function(x, ...) {
mo_validate(x = x, property = "ref", ...)
mo_is_gram_positive <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_is_gram_positive")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x.mo <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
grams <- mo_gramstain(x.mo, language = NULL)
load_mo_failures_uncertainties_renamed(metadata)
out <- grams == "Gram-positive" & !is.na(grams)
out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA
out
}
#' @rdname mo_property
#' @export
mo_authors <- function(x, ...) {
x <- mo_validate(x = x, property = "ref", ...)
mo_is_yeast <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_is_yeast")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x.mo <- as.mo(x, language = language, ...)
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)
out <- rep(FALSE, length(x))
out[x.kingdom == "Fungi" &
((x.phylum == "Ascomycetes" & x.class == "Saccharomycetes") | x.order == "Saccharomycetales")] <- TRUE
out[x.mo %in% c(NA_character_, "UNKNOWN")] <- NA
out
}
#' @rdname mo_property
#' @export
mo_is_intrinsic_resistant <- function(x, ab, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_is_intrinsic_resistant")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(ab, allow_NA = FALSE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.mo(x, language = language, ...)
ab <- as.ab(ab, language = NULL, flag_multiple_results = FALSE, info = FALSE)
if (length(x) == 1 & length(ab) > 1) {
x <- rep(x, length(ab))
} else if (length(ab) == 1 & length(x) > 1) {
ab <- rep(ab, length(x))
}
if (length(x) != length(ab)) {
stop_("length of `x` and `ab` must be equal, or one of them must be of length 1.")
}
# show used version number once per session (pkg_env will reload every session)
if (message_not_thrown_before("intrinsic_resistant_version", entire_session = TRUE)) {
message_("Determining intrinsic resistance based on ",
format_eucast_version_nr(3.2, markdown = FALSE), ". ",
font_red("This note will be shown once per session."))
remember_thrown_message("intrinsic_resistant_version", entire_session = TRUE)
}
# runs against internal vector: INTRINSIC_R (see zzz.R)
paste(x, ab) %in% INTRINSIC_R
}
#' @rdname mo_property
#' @export
mo_snomed <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_snomed")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
mo_validate(x = x, property = "snomed", language = language, ...)
}
#' @rdname mo_property
#' @export
mo_ref <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_ref")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
mo_validate(x = x, property = "ref", language = language, ...)
}
#' @rdname mo_property
#' @export
mo_authors <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_authors")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- mo_validate(x = x, property = "ref", language = language, ...)
# remove last 4 digits and presumably the comma and space that preceed them
x[!is.na(x)] <- gsub(",? ?[0-9]{4}", "", x[!is.na(x)])
suppressWarnings(x)
@@ -284,8 +523,15 @@ mo_authors <- function(x, ...) {
#' @rdname mo_property
#' @export
mo_year <- function(x, ...) {
x <- mo_validate(x = x, property = "ref", ...)
mo_year <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_year")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- mo_validate(x = x, property = "ref", language = language, ...)
# get last 4 digits
x[!is.na(x)] <- gsub(".*([0-9]{4})$", "\\1", x[!is.na(x)])
suppressWarnings(as.integer(x))
@@ -293,24 +539,38 @@ mo_year <- function(x, ...) {
#' @rdname mo_property
#' @export
mo_rank <- function(x, ...) {
mo_validate(x = x, property = "rank", ...)
mo_rank <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_rank")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
mo_validate(x = x, property = "rank", language = language, ...)
}
#' @rdname mo_property
#' @export
mo_taxonomy <- function(x, language = get_locale(), ...) {
x <- as.mo(x, ...)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_taxonomy")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
result <- base::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))
result <- 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))
load_mo_failures_uncertainties_renamed(metadata)
result
@@ -318,8 +578,15 @@ mo_taxonomy <- function(x, language = get_locale(), ...) {
#' @rdname mo_property
#' @export
mo_synonyms <- function(x, ...) {
x <- as.mo(x, ...)
mo_synonyms <- function(x, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_synonyms")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
IDs <- mo_name(x = x, language = NULL)
@@ -345,7 +612,14 @@ mo_synonyms <- function(x, ...) {
#' @rdname mo_property
#' @export
mo_info <- function(x, language = get_locale(), ...) {
x <- as.mo(x, ...)
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_info")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
x <- as.mo(x, language = language, ...)
metadata <- get_mo_failures_uncertainties_renamed()
info <- lapply(x, function(y)
@@ -367,13 +641,21 @@ mo_info <- function(x, language = get_locale(), ...) {
#' @rdname mo_property
#' @export
mo_url <- function(x, open = FALSE, ...) {
mo <- as.mo(x = x, ... = ...)
mo_url <- function(x, open = FALSE, language = get_locale(), ...) {
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_url")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(open, allow_class = "logical", has_length = 1)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE)
mo <- as.mo(x = x, language = language, ... = ...)
mo_names <- mo_name(mo)
metadata <- get_mo_failures_uncertainties_renamed()
df <- data.frame(mo, stringsAsFactors = FALSE) %>%
left_join(select(microorganisms, mo, source, species_id), by = "mo")
df <- data.frame(mo, stringsAsFactors = FALSE) %pm>%
pm_left_join(pm_select(microorganisms, mo, source, species_id), by = "mo")
df$url <- ifelse(df$source == "CoL",
paste0(catalogue_of_life$url_CoL, "details/species/id/", df$species_id, "/"),
ifelse(df$source == "DSMZ",
@@ -384,7 +666,7 @@ mo_url <- function(x, open = FALSE, ...) {
if (open == TRUE) {
if (length(u) > 1) {
warning("only the first URL will be opened, as `browseURL()` only suports one string.")
warning_("Only the first URL will be opened, as `browseURL()` only suports one string.")
}
utils::browseURL(u[1L])
}
@@ -397,17 +679,25 @@ mo_url <- function(x, open = FALSE, ...) {
#' @rdname mo_property
#' @export
mo_property <- function(x, property = "fullname", language = get_locale(), ...) {
stop_ifnot(length(property) == 1L, "'property' must be of length 1")
stop_ifnot(property %in% colnames(microorganisms),
"invalid property: '", property, "' - use a column name of the `microorganisms` data set")
if (missing(x)) {
# this tries to find the data and an <mo> column
x <- find_mo_col(fn = "mo_property")
}
meet_criteria(x, allow_NA = TRUE)
meet_criteria(property, allow_class = "character", has_length = 1, is_in = colnames(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, only_unknown = TRUE)
translate_AMR(mo_validate(x = x, property = property, language = language, ...), language = language, only_unknown = TRUE)
}
mo_validate <- function(x, property, ...) {
mo_validate <- function(x, property, language, ...) {
check_dataset_integrity()
if (tryCatch(all(x[!is.na(x)] %in% MO_lookup$mo) & length(list(...)) == 0, error = function(e) FALSE)) {
# special case for mo_* functions where class is already <mo>
return(MO_lookup[match(x, MO_lookup$mo), property, drop = TRUE])
}
dots <- list(...)
Becker <- dots$Becker
if (is.null(Becker)) {
@@ -418,28 +708,47 @@ mo_validate <- function(x, property, ...) {
Lancefield <- FALSE
}
# try to catch an error when inputting an invalid parameter
# 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))
if (is.mo(x)
& !Becker %in% c(TRUE, "all")
if (is.mo(x)
& !Becker %in% c(TRUE, "all")
& !Lancefield %in% c(TRUE, "all")) {
# this will not reset mo_uncertainties and mo_failures
# because it's already a valid MO
x <- exec_as.mo(x, property = property, initial_search = FALSE, ...)
x <- exec_as.mo(x, property = property, initial_search = FALSE, language = language, ...)
} else if (!all(x %in% MO_lookup[, property, drop = TRUE])
| Becker %in% c(TRUE, "all")
| Lancefield %in% c(TRUE, "all")) {
x <- exec_as.mo(x, property = property, ...)
x <- exec_as.mo(x, property = property, language = language, ...)
}
if (property == "mo") {
return(to_class_mo(x))
return(set_clean_class(x, new_class = c("mo", "character")))
} else if (property == "snomed") {
return(as.double(eval(parse(text = x))))
} else {
return(x)
}
}
find_mo_col <- function(fn) {
# this function tries to find an mo column in the data the function was called in,
# which is useful when functions are used within dplyr verbs
df <- get_current_data(arg_name = "x", call = -3) # will return an error if not found
mo <- NULL
try({
mo <- suppressMessages(search_type_in_df(df, "mo"))
}, silent = TRUE)
if (!is.null(df) && !is.null(mo) && is.data.frame(df)) {
if (message_not_thrown_before(fn = fn)) {
message_("Using column '", font_bold(mo), "' as input for ", fn, "()")
remember_thrown_message(fn = fn)
}
return(df[, mo, drop = TRUE])
} else {
stop_("argument `x` is missing and no column with info about microorganisms could be found.", call = -2)
}
}

View File

@@ -1,43 +1,50 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' User-defined reference data set for microorganisms
#' User-Defined Reference Data Set for Microorganisms
#'
#' @description These functions can be used to predefine your own reference to be used in [as.mo()] and consequently all `mo_*` functions like [mo_genus()] and [mo_gramstain()].
#' @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.
#' @inheritSection lifecycle Stable lifecycle
#' @param path location of your reference file, see Details. Can be `""`, `NULL` or `FALSE` to delete the reference file.
#' 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 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 seperated 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 need to have the `readxl` package installed.
#' @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 export it to `"~/.mo_source.rds"`. This compressed data file will then be used at default for MO determination (function [as.mo()] and consequently all `mo_*` functions like [mo_genus()] and [mo_gramstain()]). The location of the original file will be saved as option with `options(mo_source = path)`. Its timestamp will be saved with `options(mo_source_datetime = ...)`.
#'
#' [get_mo_source()] will return the data set by reading `"~/.mo_source.rds"` with [readRDS()]. If the original file has changed (the file defined with `path`), it will call [set_mo_source()] to update the data file automatically.
#' [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")`.
#'
#' 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 function [get_mo_source()] will return the data set by reading `"mo_source.rds"` with [readRDS()]. If the original file has changed (by checking the location and timestamp of the original file), it will call [set_mo_source()] to update the data file automatically if used in an interactive session.
#'
#' Reading an Excel file (`.xlsx`) with only one row has a size of 8-9 kB. The compressed file created with [set_mo_source()] will then have a size of 0.1 kB and can be read by [get_mo_source()] in only a couple of microseconds (millionths of a second).
#'
#' @section How to setup:
#' @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:
#'
@@ -54,16 +61,18 @@
#'
#' ```
#' set_mo_source("home/me/ourcodes.xlsx")
#' #> NOTE: Created mo_source file '~/.mo_source.rds' from 'home/me/ourcodes.xlsx'
#' #> (columns "Organisation XYZ" and "mo")
#' #> NOTE: Created mo_source file '/Users/me/mo_source.rds' (0.3 kB) from
#' #> '/Users/me/Documents/ourcodes.xlsx' (9 kB), columns
#' #> "Organisation XYZ" and "mo"
#' ```
#'
#' It has now created a file `"~/.mo_source.rds"` with the contents of our Excel file. Only the first column with foreign values and the 'mo' column will be kept when creating the RDS file.
#' It has now created a file `"~/mo_source.rds"` with the contents of our Excel file. Only the first column with foreign values and the 'mo' column will be kept when creating the RDS file.
#'
#' And now we can use it in our functions:
#'
#' ```
#' as.mo("lab_mo_ecoli")
#' #> Class <mo>
#' #> [1] B_ESCHR_COLI
#'
#' mo_genus("lab_mo_kpneumoniae")
@@ -71,6 +80,9 @@
#'
#' # other input values still work too
#' as.mo(c("Escherichia coli", "E. coli", "lab_mo_ecoli"))
#' #> NOTE: Translation to one microorganism was guessed with uncertainty.
#' #> Use mo_uncertainties() to review it.
#' #> Class <mo>
#' #> [1] B_ESCHR_COLI B_ESCHR_COLI B_ESCHR_COLI
#' ```
#'
@@ -90,8 +102,10 @@
#'
#' ```
#' as.mo("lab_mo_ecoli")
#' #> NOTE: Updated mo_source file '~/.mo_source.rds' from 'home/me/ourcodes.xlsx'
#' #> (columns "Organisation XYZ" and "mo")
#' #> NOTE: Updated mo_source file '/Users/me/mo_source.rds' (0.3 kB) from
#' #> '/Users/me/Documents/ourcodes.xlsx' (9 kB), columns
#' #> "Organisation XYZ" and "mo"
#' #> Class <mo>
#' #> [1] B_ESCHR_COLI
#'
#' mo_genus("lab_Staph_aureus")
@@ -102,38 +116,41 @@
#'
#' ```
#' set_mo_source(NULL)
#' # Removed mo_source file '~/.mo_source.rds'.
#' #> Removed mo_source file '/Users/me/mo_source.rds'
#' ```
#'
#' If the original Excel file is moved or deleted, the mo_source file will be removed upon the next use of [as.mo()]. If the mo_source file is manually deleted (i.e. without using [set_mo_source()]), the references to the mo_source file will be removed upon the next use of [as.mo()].
#' 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) {
#' @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)
stop_ifnot(destination %like% "[.]rds$", "the `destination` must be a file location with file extension .rds.")
file_location <- path.expand("~/mo_source.rds")
stop_ifnot(length(path) == 1, "`path` must be of length 1")
mo_source_destination <- path.expand(destination)
stop_ifnot(interactive(), "this function can only be used in interactive mode, since it must ask for the user's permission to write a file to their home folder.")
if (is.null(path) || path %in% c(FALSE, "")) {
options(mo_source = NULL)
options(mo_source_timestamp = NULL)
if (file.exists(file_location)) {
unlink(file_location)
message(font_red(paste0("Removed mo_source file '", font_bold(file_location), "'")))
pkg_env$mo_source <- NULL
if (file.exists(mo_source_destination)) {
unlink(mo_source_destination)
message_("Removed mo_source file '", font_bold(mo_source_destination), "'",
add_fn = font_red,
as_note = FALSE)
}
return(invisible())
}
stop_ifnot(file.exists(path),
"file not found: ", path)
stop_ifnot(file.exists(path), "file not found: ", path)
if (path %like% "[.]rds$") {
df <- readRDS(path)
} else if (path %like% "[.]xlsx?$") {
# is Excel file (old or new)
read_excel <- import_fn("read_excel", "readxl")
df <- read_excel(path)
stop_ifnot_installed("readxl")
df <- readxl::read_excel(path)
} else if (path %like% "[.]tsv$") {
df <- utils::read.table(header = TRUE, sep = "\t", stringsAsFactors = FALSE)
@@ -143,13 +160,13 @@ set_mo_source <- function(path) {
try(
df <- utils::read.table(header = TRUE, sep = ",", stringsAsFactors = FALSE),
silent = TRUE)
if (!mo_source_isvalid(df, stop_on_error = FALSE)) {
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)
}
if (!mo_source_isvalid(df, stop_on_error = FALSE)) {
if (!check_validity_mo_source(df, stop_on_error = FALSE)) {
# try pipe
try(
df <- utils::read.table(header = TRUE, sep = "|", stringsAsFactors = FALSE),
@@ -158,7 +175,7 @@ set_mo_source <- function(path) {
}
# check integrity
mo_source_isvalid(df)
check_validity_mo_source(df)
df <- subset(df, !is.na(mo))
@@ -170,79 +187,90 @@ set_mo_source <- function(path) {
}
df <- as.data.frame(df, stringAsFactors = FALSE)
df[, "mo"] <- set_clean_class(df[, "mo", drop = TRUE], c("mo", "character"))
# success
if (file.exists(file_location)) {
if (file.exists(mo_source_destination)) {
action <- "Updated"
} else {
action <- "Created"
# only ask when file is created, not when it is updated
txt <- paste0(word_wrap(paste0("This will write create the new file '",
mo_source_destination,
"', for which your permission is needed.")),
"\n\n",
word_wrap("Do you agree that this file will be created?"))
if ("rsasdtudioapi" %in% rownames(utils::installed.packages())) {
showQuestion <- import_fn("showQuestion", "rstudioapi")
q_continue <- showQuestion("Create new file in home directory", txt)
} else {
q_continue <- utils::menu(choices = c("OK", "Cancel"), graphics = FALSE, title = txt)
}
if (q_continue %in% c(FALSE, 2)) {
return(invisible())
}
}
saveRDS(df, file_location)
options(mo_source = path)
options(mo_source_timestamp = as.character(file.info(path)$mtime))
message(font_blue(paste0("NOTE: ",
action, " mo_source file '", font_bold(file_location), "'",
" from '", font_bold(path), "'",
'\n (columns "', colnames(df)[1], '" and "', colnames(df)[2], '")')))
attr(df, "mo_source_location") <- path
attr(df, "mo_source_destination") <- mo_source_destination
attr(df, "mo_source_timestamp") <- file.mtime(path)
saveRDS(df, mo_source_destination)
pkg_env$mo_source <- df
message_(action, " mo_source file '", font_bold(mo_source_destination),
"' (", formatted_filesize(mo_source_destination),
") from '", font_bold(path),
"' (", formatted_filesize(path),
'), columns "', colnames(df)[1], '" and "', colnames(df)[2], '"')
}
#' @rdname mo_source
#' @export
get_mo_source <- function() {
if (is.null(getOption("mo_source", NULL))) {
get_mo_source <- function(destination = getOption("AMR_mo_source", "~/mo_source.rds")) {
if (!file.exists(path.expand(destination))) {
if (interactive()) {
# source file might have been deleted, so update reference
set_mo_source("")
}
return(NULL)
}
if (!file.exists(path.expand("~/mo_source.rds"))) {
options(mo_source = NULL)
options(mo_source_timestamp = NULL)
message(font_blue("NOTE: Removed references to deleted mo_source file (see ?mo_source)"))
return(NULL)
if (is.null(pkg_env$mo_source)) {
pkg_env$mo_source <- readRDS(path.expand(destination))
}
old_time <- as.POSIXct(getOption("mo_source_timestamp"))
new_time <- as.POSIXct(as.character(file.info(getOption("mo_source", ""))$mtime))
if (is.na(new_time)) {
# source file was deleted, remove reference too
set_mo_source("")
return(NULL)
old_time <- attributes(pkg_env$mo_source)$mo_source_timestamp
new_time <- file.mtime(attributes(pkg_env$mo_source)$mo_source_location)
if (interactive() && !identical(old_time, new_time)) {
# source file was updated, also update reference
set_mo_source(attributes(pkg_env$mo_source)$mo_source_location)
}
if (new_time != old_time) {
# set updated source
set_mo_source(getOption("mo_source"))
}
file_location <- path.expand("~/mo_source.rds")
readRDS(file_location)
pkg_env$mo_source
}
mo_source_isvalid <- function(x, refer_to_name = "`reference_df`", stop_on_error = TRUE) {
check_validity_mo_source <- function(x, refer_to_name = "`reference_df`", stop_on_error = TRUE) {
check_dataset_integrity()
if (deparse(substitute(x)) == "get_mo_source()") {
if (paste(deparse(substitute(x)), collapse = "") == "get_mo_source()") {
return(TRUE)
}
if (identical(x, get_mo_source())) {
if (is.null(pkg_env$mo_source) && (identical(x, get_mo_source()))) {
return(TRUE)
}
if (is.null(x)) {
if (stop_on_error == TRUE) {
stop(refer_to_name, " cannot be NULL", call. = FALSE)
stop_(refer_to_name, " cannot be NULL", call = FALSE)
} else {
return(FALSE)
}
}
if (!is.data.frame(x)) {
if (stop_on_error == TRUE) {
stop(refer_to_name, " must be a data.frame", call. = FALSE)
stop_(refer_to_name, " must be a data.frame", call = FALSE)
} else {
return(FALSE)
}
}
if (!"mo" %in% colnames(x)) {
if (stop_on_error == TRUE) {
stop(refer_to_name, " must contain a column 'mo'", call. = FALSE)
stop_(refer_to_name, " must contain a column 'mo'", call = FALSE)
} else {
return(FALSE)
}
@@ -255,13 +283,27 @@ mo_source_isvalid <- function(x, refer_to_name = "`reference_df`", stop_on_error
} else {
plural <- ""
}
stop("Value", plural, " ", paste0("'", invalid[, 1, drop = TRUE], "'", collapse = ", "),
stop_("Value", plural, " ", paste0("'", invalid[, 1, drop = TRUE], "'", collapse = ", "),
" found in ", tolower(refer_to_name),
", but with invalid microorganism code", plural, " ", paste0("'", invalid$mo, "'", collapse = ", "),
call. = FALSE)
call = FALSE)
} else {
return(FALSE)
}
}
TRUE
if (colnames(x)[1] != "mo" & nrow(x) > length(unique(x[, 1, drop = TRUE]))) {
if (stop_on_error == TRUE) {
stop_(refer_to_name, " contains duplicate values in column '", colnames(x)[1], "'", call = FALSE)
} else {
return(FALSE)
}
}
if (colnames(x)[2] != "mo" & nrow(x) > length(unique(x[, 2, drop = TRUE]))) {
if (stop_on_error == TRUE) {
stop_(refer_to_name, " contains duplicate values in column '", colnames(x)[2], "'", call = FALSE)
} else {
return(FALSE)
}
}
return(TRUE)
}

80
R/pca.R
View File

@@ -1,28 +1,32 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Principal Component Analysis (for AMR)
#'
#' Performs a principal component analysis (PCA) based on a data set with automatic determination for afterwards plotting the groups and labels, and automatic filtering on only suitable (i.e. non-empty and numeric) variables.
#' @inheritSection lifecycle Maturing lifecycle
#' @inheritSection lifecycle Maturing 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
@@ -32,26 +36,29 @@
#' @return An object of classes [pca] and [prcomp]
#' @importFrom stats prcomp
#' @export
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # `example_isolates` is a dataset available in the AMR package.
#' # See ?example_isolates.
#'
#' \dontrun{
#' # calculate the resistance per group first
#' library(dplyr)
#' 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
#' summarise_if(is.rsi, resistance) # then get resistance of all drugs
#'
#' # now conduct PCA for certain antimicrobial agents
#' pca_result <- resistance_data %>%
#' pca(AMC, CXM, CTX, CAZ, GEN, TOB, TMP, SXT)
#'
#' pca_result
#' summary(pca_result)
#' biplot(pca_result)
#' ggplot_pca(pca_result) # a new and convenient plot function
#' \donttest{
#'
#' if (require("dplyr")) {
#' # calculate the resistance per group first
#' resistance_data <- example_isolates %>%
#' group_by(order = mo_order(mo), # group on anything, like order
#' genus = mo_genus(mo)) %>% # and genus as we do here
#' summarise_if(is.rsi, resistance) # then get resistance of all drugs
#'
#' # now conduct PCA for certain antimicrobial agents
#' pca_result <- resistance_data %>%
#' pca(AMC, CXM, CTX, CAZ, GEN, TOB, TMP, SXT)
#'
#' pca_result
#' summary(pca_result)
#' biplot(pca_result)
#' ggplot_pca(pca_result) # a new and convenient plot function
#' }
#' }
pca <- function(x,
...,
@@ -60,9 +67,12 @@ pca <- function(x,
scale. = TRUE,
tol = NULL,
rank. = NULL) {
stop_ifnot(is.data.frame(x), "`x` must be a data.frame")
stop_if(any(dim(x) == 0), "`x` must contain rows and columns")
meet_criteria(x, allow_class = "data.frame")
meet_criteria(retx, allow_class = "logical", has_length = 1)
meet_criteria(center, allow_class = "logical", has_length = 1)
meet_criteria(scale., allow_class = "logical", has_length = 1)
meet_criteria(tol, allow_class = "numeric", has_length = 1, allow_NULL = TRUE)
meet_criteria(rank., allow_class = "numeric", has_length = 1, allow_NULL = TRUE)
# unset data.table, tibble, etc.
# also removes groups made by dplyr::group_by
@@ -78,18 +88,18 @@ pca <- function(x,
error = function(e) stop(e$message, call. = FALSE))
if (length(new_list[[i]]) == 1) {
if (is.character(new_list[[i]]) & new_list[[i]] %in% colnames(x)) {
# this is to support quoted variables: df %>% pca("mycol1", "mycol2")
# this is to support quoted variables: df %pm>% pca("mycol1", "mycol2")
new_list[[i]] <- x[, new_list[[i]]]
} else {
# remove item - it's a parameter like `center`
# remove item - it's a argument like `center`
new_list[[i]] <- NULL
}
}
}
x <- as.data.frame(new_list, stringsAsFactors = FALSE)
if (any(sapply(x, function(y) !is.numeric(y)))) {
warning("Be sure to first calculate the resistance (or susceptibility) of variables with antimicrobial test results, since PCA works with numeric variables only. Please see Examples in ?pca.")
if (any(vapply(FUN.VALUE = logical(1), x, function(y) !is.numeric(y)))) {
warning_("Be sure to first calculate the resistance (or susceptibility) of variables with antimicrobial test results, since PCA works with numeric variables only. See Examples in ?pca.")
}
# set column names
@@ -97,21 +107,21 @@ pca <- function(x,
error = function(e) warning("column names could not be set"))
# keep only numeric columns
x <- x[, sapply(x, function(y) is.numeric(y))]
x <- x[, vapply(FUN.VALUE = logical(1), x, function(y) is.numeric(y))]
# bind the data set with the non-numeric columns
x <- cbind(x.bak[, sapply(x.bak, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE], x)
x <- cbind(x.bak[, vapply(FUN.VALUE = logical(1), x.bak, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE], x)
}
x <- ungroup(x) # would otherwise select the grouping vars
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(sapply(x, function(x) is.numeric(x)))]
pca_data <- x[, which(vapply(FUN.VALUE = logical(1), x, function(x) is.numeric(x)))]
message(font_blue(paste0("NOTE: Columns selected for PCA: ", paste0(font_bold(colnames(pca_data)), collapse = "/"),
".\n Total observations available: ", nrow(pca_data), ".")))
message_("Columns selected for PCA: ", paste0(font_bold(colnames(pca_data)), collapse = "/"),
". Total observations available: ", nrow(pca_data), ".")
pca_model <- prcomp(pca_data, retx = retx, center = center, scale. = scale., tol = tol, rank. = rank.)
attr(pca_model, "non_numeric_cols") <- x[, sapply(x, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE]
attr(pca_model, "non_numeric_cols") <- x[, vapply(FUN.VALUE = logical(1), x, function(y) !is.numeric(y) & !all(is.na(y))), drop = FALSE]
class(pca_model) <- c("pca", class(pca_model))
pca_model
}

View File

@@ -1,50 +1,54 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Calculate microbial resistance
#' Calculate Microbial Resistance
#'
#' @description These functions can be used to calculate the (co-)resistance or susceptibility of microbial isolates (i.e. percentage of S, SI, I, IR or R). All functions support quasiquotation with pipes, can be used in `summarise()` from the `dplyr` package and also support grouped variables, please see *Examples*.
#' @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.
#' @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%"`.
#' @param only_all_tested (for combination therapies, i.e. using more than one variable for `...`): a logical to indicate that isolates must be tested for all antibiotics, see section *Combination therapy* below
#' @param data a [`data.frame`] containing columns with class [`rsi`] (see [as.rsi()])
#' @param translate_ab a column name of the [antibiotics] data set to translate the antibiotic abbreviations to, using [ab_property()]. Use a value
#' @param only_all_tested (for combination therapies, i.e. using more than one variable for `...`): a logical to indicate that isolates must be tested for all antibiotics, see section *Combination Therapy* below
#' @param data a [data.frame] containing columns with class [`rsi`] (see [as.rsi()])
#' @param translate_ab a column name of the [antibiotics] data set to translate the antibiotic abbreviations to, using [ab_property()]
#' @inheritParams ab_property
#' @param combine_SI a logical to indicate whether all values of S and I must be merged into one, so the output only consists of S+I vs. R (susceptible vs. resistant). This used to be the parameter `combine_IR`, but this now follows the redefinition by EUCAST about the interpretion of I (increased exposure) in 2019, see section 'Interpretation of S, I and R' below. Default is `TRUE`.
#' @param combine_IR a logical to indicate whether all values of I and R must be merged into one, so the output only consists of S vs. I+R (susceptible vs. non-susceptible). This is outdated, see parameter `combine_SI`.
#' @param combine_SI a logical to indicate whether all values of S and I must be merged into one, so the output only consists of S+I vs. R (susceptible vs. resistant). This used to be the argument `combine_IR`, but this now follows the redefinition by EUCAST about the interpretation of I (increased exposure) in 2019, see section 'Interpretation of S, I and R' below. Default is `TRUE`.
#' @param combine_IR a logical to indicate whether all values of I and R must be merged into one, so the output only consists of S vs. I+R (susceptible vs. non-susceptible). This is outdated, see argument `combine_SI`.
#' @inheritSection as.rsi Interpretation of R and S/I
#' @details
#' The function [resistance()] is equal to the function [proportion_R()]. The function [susceptibility()] is equal to the function [proportion_SI()].
#'
#' **Remember that you should filter your table to let it contain only first isolates!** This is needed to exclude duplicates and to reduce selection bias. Use [first_isolate()] to determine them in your data set.
#'
#' These functions are not meant to count isolates, but to calculate the proportion of resistance/susceptibility. Use the [`count()`][AMR::count()] functions to count isolates. The function [susceptibility()] is essentially equal to `count_susceptible() / count_all()`. *Low counts can influence the outcome - the `proportion` functions may camouflage this, since they only return the proportion (albeit being dependent on the `minimum` parameter).*
#' These functions are not meant to count isolates, but to calculate the proportion of resistance/susceptibility. Use the [`count()`][AMR::count()] functions to count isolates. The function [susceptibility()] is essentially equal to `count_susceptible() / count_all()`. *Low counts can influence the outcome - the `proportion` functions may camouflage this, since they only return the proportion (albeit being dependent on the `minimum` argument).*
#'
#' The function [proportion_df()] takes any variable from `data` that has an [`rsi`] class (created with [as.rsi()]) and calculates the proportions R, I and S. It also supports grouped variables. The function [rsi_df()] works exactly like [proportion_df()], but adds the number of isolates.
#' @section Combination therapy:
#' When using more than one variable for `...` (= combination therapy)), use `only_all_tested` to only count isolates that are tested for all antibiotics/variables that you test them for. See this example for two antibiotics, Drug A and Drug B, about how [susceptibility()] works to calculate the %SI:
#' @section Combination Therapy:
#' When using more than one variable for `...` (= combination therapy), use `only_all_tested` to only count isolates that are tested for all antibiotics/variables that you test them for. See this example for two antibiotics, Drug A and Drug B, about how [susceptibility()] works to calculate the %SI:
#'
#' ```
#' --------------------------------------------------------------------
@@ -79,12 +83,12 @@
#' Using `only_all_tested` has no impact when only using one antibiotic as input.
#' @source **M39 Analysis and Presentation of Cumulative Antimicrobial Susceptibility Test Data, 4th Edition**, 2014, *Clinical and Laboratory Standards Institute (CLSI)*. <https://clsi.org/standards/products/microbiology/documents/m39/>.
#' @seealso [AMR::count()] to count resistant and susceptible isolates.
#' @return A [`double`] or, when `as_percent = TRUE`, a [`character`].
#' @return A [double] or, when `as_percent = TRUE`, a [character].
#' @rdname proportion
#' @aliases portion
#' @name proportion
#' @export
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' # example_isolates is a data set available in the AMR package.
#' ?example_isolates
@@ -157,15 +161,6 @@
#' group_by(hospital_id) %>%
#' proportion_df(translate = FALSE)
#' }
#'
#' \dontrun{
#' # calculate current empiric combination therapy of Helicobacter gastritis:
#' my_table %>%
#' filter(first_isolate == TRUE,
#' genus == "Helicobacter") %>%
#' summarise(p = susceptibility(AMX, MTR), # amoxicillin with metronidazole
#' n = count_all(AMX, MTR))
#' }
resistance <- function(...,
minimum = 30,
as_percent = FALSE,
@@ -271,7 +266,6 @@ proportion_df <- function(data,
as_percent = FALSE,
combine_SI = TRUE,
combine_IR = FALSE) {
rsi_calc_df(type = "proportion",
data = data,
translate_ab = translate_ab,

132
R/random.R Normal file
View File

@@ -0,0 +1,132 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Random MIC Values/Disk Zones/RSI Generation
#'
#' These functions can be used for generating random MIC values and disk diffusion diameters, for AMR analysis practice.
#' @inheritSection lifecycle Maturing Lifecycle
#' @param size desired size of the returned vector
#' @param mo any character that can be coerced to a valid microorganism code with [as.mo()]
#' @param ab any character that can be coerced to a valid antimicrobial agent code with [as.ab()]
#' @param prob_RSI a vector of length 3: the probabilities for R (1st value), S (2nd value) and I (3rd value)
#' @param ... extension for future versions, not used at the moment
#' @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.
#' @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)
#'
#' \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_disk(100, "Klebsiella pneumoniae") # range 11-50
#' random_disk(100, "Klebsiella pneumoniae", "ampicillin") # range 6-14
#' random_disk(100, "Streptococcus pneumoniae", "ampicillin") # range 16-22
#' }
random_mic <- function(size, mo = NULL, ab = NULL, ...) {
random_exec("MIC", size = size, mo = mo, ab = ab)
}
#' @rdname random
#' @export
random_disk <- function(size, mo = NULL, ab = NULL, ...) {
random_exec("DISK", size = size, mo = mo, ab = ab)
}
#' @rdname random
#' @export
random_rsi <- function(size, prob_RSI = c(0.33, 0.33, 0.33), ...) {
sample(as.rsi(c("R", "S", "I")), size = size, replace = TRUE, prob = prob_RSI)
}
random_exec <- function(type, size, mo = NULL, ab = NULL) {
df <- rsi_translation %pm>%
pm_filter(guideline %like% "EUCAST") %pm>%
pm_arrange(pm_desc(guideline)) %pm>%
subset(guideline == max(guideline) &
method == type)
if (!is.null(mo)) {
mo_coerced <- as.mo(mo)
mo_include <- c(mo_coerced,
as.mo(mo_genus(mo_coerced)),
as.mo(mo_family(mo_coerced)),
as.mo(mo_order(mo_coerced)))
df_new <- df %pm>%
subset(mo %in% mo_include)
if (nrow(df_new) > 0) {
df <- df_new
} else {
warning_("No rows found that match mo '", mo, "', ignoring argument `mo`", call = FALSE)
}
}
if (!is.null(ab)) {
ab_coerced <- as.ab(ab)
df_new <- df %pm>%
subset(ab %in% ab_coerced)
if (nrow(df_new) > 0) {
df <- df_new
} else {
warning_("No rows found that match ab '", ab, "', ignoring argument `ab`", call = FALSE)
}
}
if (type == "MIC") {
# all valid MIC levels
valid_range <- as.mic(levels(as.mic(1)))
set_range_max <- max(df$breakpoint_R)
if (log(set_range_max, 2) %% 1 == 0) {
# return powers of 2
valid_range <- unique(as.double(valid_range))
# add one higher MIC level to set_range_max
set_range_max <- 2 ^ (log(set_range_max, 2) + 1)
set_range <- as.mic(valid_range[log(valid_range, 2) %% 1 == 0 & valid_range <= set_range_max])
} else {
# no power of 2, return factors of 2 to left and right side
valid_mics <- suppressWarnings(as.mic(set_range_max / (2 ^ c(-3:3))))
set_range <- valid_mics[!is.na(valid_mics)]
}
return(as.mic(sample(set_range, size = size, replace = TRUE)))
} else if (type == "DISK") {
set_range <- seq(from = as.integer(min(df$breakpoint_R)),
to = as.integer(max(df$breakpoint_S)),
by = 1)
out <- sample(set_range, size = size, replace = TRUE)
out[out < 6] <- sample(c(6:10), length(out[out < 6]), replace = TRUE)
out[out > 50] <- sample(c(40:50), length(out[out > 50]), replace = TRUE)
return(as.disk(out))
}
}

View File

@@ -1,49 +1,53 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Predict antimicrobial resistance
#'
#' Create a prediction model to predict antimicrobial resistance for the next years on statistical solid ground. Standard errors (SE) will be returned as columns `se_min` and `se_max`. See *Examples* for a real live example.
#' @inheritSection lifecycle Maturing lifecycle
#' @inheritSection lifecycle Maturing Lifecycle
#' @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
#' @param year_min lowest year to use in the prediction model, dafaults to the lowest year in `col_date`
#' @param year_max highest year to use in the prediction model, 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 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 interpretion of I (increased exposure) in 2019, see section *Interpretation of S, I and R* below.
#' @param model the statistical model of choice. This could be a generalised linear regression model with binomial distribution (i.e. using `glm(..., family = binomial)``, assuming that a period of zero resistance was followed by a period of increasing resistance leading slowly to more and more resistance. See *Details* for all valid options.
#' @param I_as_S a logical to indicate whether values `"I"` should be treated as `"S"` (will otherwise be treated as `"R"`). The default, `TRUE`, follows the redefinition by EUCAST about the interpretation of I (increased exposure) in 2019, see section *Interpretation of S, I and R* below.
#' @param preserve_measurements a logical to indicate whether predictions of years that are actually available in the data should be overwritten by the original data. The standard errors of those years will be `NA`.
#' @param info a logical to indicate whether textual analysis should be printed with the name and [summary()] of the statistical model.
#' @param main title of the plot
#' @param ribbon a logical to indicate whether a ribbon should be shown (default) or error bars
#' @param ... parameters passed on to functions
#' @param ... arguments passed on to functions
#' @inheritSection as.rsi Interpretation of R and S/I
#' @inheritParams first_isolate
#' @inheritParams graphics::plot
#' @details Valid options for the statistical model (parameter `model`) are:
#' @details Valid options for the statistical model (argument `model`) are:
#' - `"binomial"` or `"binom"` or `"logit"`: a generalised linear regression model with binomial distribution
#' - `"loglin"` or `"poisson"`: a generalised log-linear regression model with poisson distribution
#' - `"lin"` or `"linear"`: a linear regression model
#' @return A [`data.frame`] with extra class [`resistance_predict`] with columns:
#' @return A [data.frame] with extra class [`resistance_predict`] with columns:
#' - `year`
#' - `value`, the same as `estimated` when `preserve_measurements = FALSE`, and a combination of `observed` and `estimated` otherwise
#' - `se_min`, the lower bound of the standard error with a minimum of `0` (so the standard error will never go below 0%)
@@ -52,14 +56,14 @@
#' - `observed`, the original observed resistant percentages
#' - `estimated`, the estimated resistant percentages, calculated by the model
#'
#' Furthermore, the model itself is available as an attribute: `attributes(x)$model`, please see *Examples*.
#' Furthermore, the model itself is available as an attribute: `attributes(x)$model`, see *Examples*.
#' @seealso The [proportion()] functions to calculate resistance
#'
#' Models: [lm()] [glm()]
#' @rdname resistance_predict
#' @export
#' @importFrom stats predict glm lm
#' @inheritSection AMR Read more on our website!
#' @inheritSection AMR Read more on Our Website!
#' @examples
#' x <- resistance_predict(example_isolates,
#' col_ab = "AMX",
@@ -84,10 +88,8 @@
#' }
#'
#' # create nice plots with ggplot2 yourself
#' \dontrun{
#' library(dplyr)
#' library(ggplot2)
#'
#' if (require("dplyr") & require("ggplot2")) {
#'
#' data <- example_isolates %>%
#' filter(mo == as.mo("E. coli")) %>%
#' resistance_predict(col_ab = "AMX",
@@ -124,22 +126,29 @@ resistance_predict <- function(x,
preserve_measurements = TRUE,
info = interactive(),
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(col_ab, allow_class = "character", has_length = 1, is_in = colnames(x))
meet_criteria(col_date, allow_class = "character", has_length = 1, is_in = colnames(x), allow_NULL = TRUE)
meet_criteria(year_min, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE)
meet_criteria(year_max, allow_class = c("numeric", "integer"), has_length = 1, allow_NULL = TRUE)
meet_criteria(year_every, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1)
meet_criteria(model, allow_class = c("character", "function"), has_length = 1, allow_NULL = TRUE)
meet_criteria(I_as_S, allow_class = "logical", has_length = 1)
meet_criteria(preserve_measurements, allow_class = "logical", has_length = 1)
meet_criteria(info, allow_class = "logical", has_length = 1)
stop_ifnot(is.data.frame(x), "`x` must be a data.frame")
stop_if(any(dim(x) == 0), "`x` must contain rows and columns")
stop_if(is.null(model), 'choose a regression model with the `model` parameter, e.g. resistance_predict(..., model = "binomial")')
stop_ifnot(col_ab %in% colnames(x),
"column `", col_ab, "` not found")
stop_if(is.null(model), 'choose a regression model with the `model` argument, e.g. resistance_predict(..., model = "binomial")')
dots <- unlist(list(...))
if (length(dots) != 0) {
# backwards compatibility with old parameters
dots.names <- dots %>% names()
# backwards compatibility with old arguments
dots.names <- dots %pm>% names()
if ("tbl" %in% dots.names) {
x <- dots[which(dots.names == "tbl")]
}
if ("I_as_R" %in% dots.names) {
warning("`I_as_R is deprecated - use I_as_S instead.", call. = FALSE)
warning_("`I_as_R is deprecated - use I_as_S instead.", call = FALSE)
}
}
@@ -149,7 +158,7 @@ resistance_predict <- function(x,
stop_if(is.null(col_date), "`col_date` must be set")
}
stop_ifnot(col_date %in% colnames(x),
"column `", col_date, "` not found")
"column '", col_date, "' not found")
# no grouped tibbles
x <- as.data.frame(x, stringsAsFactors = FALSE)
@@ -177,12 +186,15 @@ 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)])),
stringsAsFactors = FALSE)
df$year <- as.integer(rownames(df))
rownames(df) <- NULL
df <- subset(df, sum(df$R + df$S, na.rm = TRUE) >= minimum)
# nolint start
df_matrix <- as.matrix(df[, c("R", "S"), drop = FALSE])
# nolint end
stop_if(NROW(df) == 0, "there are no observations")
@@ -264,8 +276,8 @@ resistance_predict <- function(x,
observations = df$R + df$S,
observed = df$R / (df$R + df$S),
stringsAsFactors = FALSE)
df_prediction <- df_prediction %>%
left_join(df_observations, by = "year")
df_prediction <- df_prediction %pm>%
pm_left_join(df_observations, by = "year")
df_prediction$estimated <- df_prediction$value
if (preserve_measurements == TRUE) {
@@ -294,22 +306,18 @@ rsi_predict <- resistance_predict
#' @method plot resistance_predict
#' @export
#' @importFrom graphics axis arrows points
#' @importFrom graphics plot axis arrows points
#' @rdname resistance_predict
plot.resistance_predict <- function(x, main = paste("Resistance Prediction of", x_name), ...) {
x_name <- paste0(ab_name(attributes(x)$ab), " (", attributes(x)$ab, ")")
meet_criteria(main, allow_class = "character", has_length = 1)
if (attributes(x)$I_as_S == TRUE) {
ylab <- "%R"
} else {
ylab <- "%IR"
}
# get plot() generic; this was moved from the 'graphics' pkg to the 'base' pkg in R 4.0.0
if (as.integer(R.Version()$major) >= 4) {
plot <- import_fn("plot", "base")
} else {
plot <- import_fn("plot", "graphics")
}
plot(x = x$year,
y = x$value,
ylim = c(0, 1),
@@ -345,11 +353,13 @@ ggplot_rsi_predict <- function(x,
main = paste("Resistance Prediction of", x_name),
ribbon = TRUE,
...) {
x_name <- paste0(ab_name(attributes(x)$ab), " (", attributes(x)$ab, ")")
meet_criteria(main, allow_class = "character", has_length = 1)
meet_criteria(ribbon, allow_class = "logical", has_length = 1)
stop_ifnot_installed("ggplot2")
stop_ifnot(inherits(x, "resistance_predict"), "`x` must be a resistance prediction model created with resistance_predict()")
x_name <- paste0(ab_name(attributes(x)$ab), " (", attributes(x)$ab, ")")
if (attributes(x)$I_as_S == TRUE) {
ylab <- "%R"

875
R/rsi.R

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
dots2vars <- function(...) {
@@ -32,10 +36,11 @@ rsi_calc <- function(...,
as_percent = FALSE,
only_all_tested = FALSE,
only_count = FALSE) {
stop_ifnot(is.numeric(minimum), "`minimum` must be numeric", call = -2)
stop_ifnot(is.logical(as_percent), "`as_percent` must be logical", call = -2)
stop_ifnot(is.logical(only_all_tested), "`only_all_tested` must be logical", call = -2)
meet_criteria(ab_result, allow_class = c("character", "numeric", "integer"), has_length = c(1, 2, 3), .call_depth = 1)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, .call_depth = 1)
meet_criteria(as_percent, allow_class = "logical", has_length = 1, .call_depth = 1)
meet_criteria(only_all_tested, allow_class = "logical", has_length = 1, .call_depth = 1)
meet_criteria(only_count, allow_class = "logical", has_length = 1, .call_depth = 1)
data_vars <- dots2vars(...)
@@ -45,7 +50,7 @@ rsi_calc <- function(...,
dots_df <- as.data.frame(dots_df, stringsAsFactors = FALSE)
}
dots <- base::eval(base::substitute(base::alist(...)))
dots <- eval(substitute(alist(...)))
stop_if(length(dots) == 0, "no variables selected", call = -2)
stop_if("also_single_tested" %in% names(dots),
@@ -54,7 +59,7 @@ rsi_calc <- function(...,
ndots <- length(dots)
if (is.data.frame(dots_df)) {
# data.frame passed with other columns, like: example_isolates %>% proportion_S(AMC, GEN)
# data.frame passed with other columns, like: example_isolates %pm>% proportion_S(AMC, GEN)
dots <- as.character(dots)
# remove first element, it's the data.frame
@@ -64,12 +69,12 @@ rsi_calc <- function(...,
dots <- dots[2:length(dots)]
}
if (length(dots) == 0 | all(dots == "df")) {
# for complete data.frames, like example_isolates %>% select(AMC, GEN) %>% proportion_S()
# and the old rsi function, which has "df" as name of the first parameter
# for complete data.frames, like example_isolates %pm>% select(AMC, GEN) %pm>% proportion_S()
# and the old rsi function, which has "df" as name of the first argument
x <- dots_df
} else {
# get dots that are in column names already, and the ones that will be once evaluated using dots_df or global env
# this is to support susceptibility(example_isolates, AMC, dplyr::all_of(some_vector_with_AB_names))
# this is to support susceptibility(example_isolates, AMC, any_of(some_vector_with_AB_names))
dots <- c(dots[dots %in% colnames(dots_df)],
eval(parse(text = dots[!dots %in% colnames(dots_df)]), envir = dots_df, enclos = globalenv()))
dots_not_exist <- dots[!dots %in% colnames(dots_df)]
@@ -77,21 +82,25 @@ rsi_calc <- function(...,
x <- dots_df[, dots, drop = FALSE]
}
} else if (ndots == 1) {
# only 1 variable passed (can also be data.frame), like: proportion_S(example_isolates$AMC) and example_isolates$AMC %>% proportion_S()
# only 1 variable passed (can also be data.frame), like: proportion_S(example_isolates$AMC) and example_isolates$AMC %pm>% proportion_S()
x <- dots_df
} else {
# multiple variables passed without pipe, like: proportion_S(example_isolates$AMC, example_isolates$GEN)
x <- NULL
try(x <- as.data.frame(dots, stringsAsFactors = FALSE), silent = TRUE)
if (is.null(x)) {
# support for example_isolates %>% group_by(hospital_id) %>% summarise(amox = susceptibility(GEN, AMX))
# support for example_isolates %pm>% group_by(hospital_id) %pm>% summarise(amox = susceptibility(GEN, AMX))
x <- as.data.frame(list(...), stringsAsFactors = FALSE)
}
}
if (is.null(x)) {
warning("argument is NULL (check if columns exist): returning NA", call. = FALSE)
return(NA)
warning_("argument is NULL (check if columns exist): returning NA", call = FALSE)
if (as_percent == TRUE) {
return(NA_character_)
} else {
return(NA_real_)
}
}
print_warning <- FALSE
@@ -113,19 +122,19 @@ rsi_calc <- function(...,
rsi_integrity_check <- as.rsi(rsi_integrity_check)
}
x_transposed <- as.list(as.data.frame(t(x)))
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),
MARGIN = 1,
FUN = base::min)
FUN = min)
numerator <- sum(as.integer(y) %in% as.integer(ab_result), na.rm = TRUE)
denominator <- sum(sapply(x_transposed, function(y) !(any(is.na(y)))))
denominator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) !(any(is.na(y)))))
} else {
# may contain NAs in any column
other_values <- base::setdiff(c(NA, levels(ab_result)), ab_result)
numerator <- sum(sapply(x_transposed, function(y) any(y %in% ab_result, na.rm = TRUE)))
denominator <- sum(sapply(x_transposed, function(y) !(all(y %in% other_values) & any(is.na(y)))))
other_values <- setdiff(c(NA, levels(ab_result)), ab_result)
numerator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) any(y %in% ab_result, na.rm = TRUE)))
denominator <- sum(vapply(FUN.VALUE = logical(1), x_transposed, function(y) !(all(y %in% other_values) & any(is.na(y)))))
}
} else {
# x is not a data.frame
@@ -138,8 +147,13 @@ rsi_calc <- function(...,
}
if (print_warning == TRUE) {
warning("Increase speed by transforming to class <rsi> on beforehand: your_data %>% mutate_if(is.rsi.eligible, as.rsi)",
call. = FALSE)
if (message_not_thrown_before("rsi_calc")) {
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((is.rsi.eligible), as.rsi))",
call = FALSE)
remember_thrown_message("rsi_calc")
}
}
if (only_count == TRUE) {
@@ -150,10 +164,11 @@ rsi_calc <- function(...,
if (data_vars != "") {
data_vars <- paste(" for", data_vars)
}
warning("Introducing NA: only ", denominator, " results available", data_vars, " (`minimum` = ", minimum, ").", call. = FALSE)
fraction <- NA
warning_("Introducing NA: only ", denominator, " results available", data_vars, " (`minimum` = ", minimum, ").", call = FALSE)
fraction <- NA_real_
} else {
fraction <- numerator / denominator
fraction[is.nan(fraction)] <- NA_real_
}
if (as_percent == TRUE) {
@@ -172,28 +187,32 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
combine_SI = TRUE,
combine_IR = FALSE,
combine_SI_missing = FALSE) {
meet_criteria(type, is_in = c("proportion", "count", "both"), has_length = 1, .call_depth = 1)
meet_criteria(data, allow_class = "data.frame", contains_column_class = "rsi", .call_depth = 1)
meet_criteria(translate_ab, allow_class = c("character", "logical"), has_length = 1, allow_NA = TRUE, .call_depth = 1)
meet_criteria(language, has_length = 1, is_in = c(LANGUAGES_SUPPORTED, ""), allow_NULL = TRUE, allow_NA = TRUE, .call_depth = 1)
meet_criteria(minimum, allow_class = c("numeric", "integer"), has_length = 1, .call_depth = 1)
meet_criteria(as_percent, allow_class = "logical", has_length = 1, .call_depth = 1)
meet_criteria(combine_SI, allow_class = "logical", has_length = 1, .call_depth = 1)
meet_criteria(combine_SI_missing, allow_class = "logical", has_length = 1, .call_depth = 1)
check_dataset_integrity()
stop_ifnot(is.data.frame(data), "`data` must be a data.frame", call = -2)
stop_if(any(dim(data) == 0), "`data` must contain rows and columns", call = -2)
stop_ifnot(any(sapply(data, is.rsi), na.rm = TRUE), "no columns with class <rsi> found. See ?as.rsi.", call = -2)
if (isTRUE(combine_IR) & isTRUE(combine_SI_missing)) {
combine_SI <- FALSE
}
stop_if(isTRUE(combine_SI) & isTRUE(combine_IR), "either `combine_SI` or `combine_IR` can be TRUE, not both", call = -2)
stop_ifnot(is.numeric(minimum), "`minimum` must be numeric", call = -2)
stop_ifnot(is.logical(as_percent), "`as_percent` must be logical", call = -2)
translate_ab <- get_translate_ab(translate_ab)
# select only groups and antibiotics
if (has_groups(data)) {
if (inherits(data, "grouped_df")) {
data_has_groups <- TRUE
groups <- setdiff(names(get_groups(data)), ".rows") # get_groups is from poorman.R
data <- data[, c(groups, colnames(data)[sapply(data, is.rsi)]), drop = FALSE]
groups <- setdiff(names(attributes(data)$groups), ".rows")
data <- data[, c(groups, colnames(data)[vapply(FUN.VALUE = logical(1), data, is.rsi)]), drop = FALSE]
} else {
data_has_groups <- FALSE
data <- data[, colnames(data)[sapply(data, is.rsi)], drop = FALSE]
data <- data[, colnames(data)[vapply(FUN.VALUE = logical(1), data, is.rsi)], drop = FALSE]
}
data <- as.data.frame(data, stringsAsFactors = FALSE)
@@ -230,7 +249,7 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
} else {
values <- factor(values, levels = c("S", "I", "R"), ordered = TRUE)
}
col_results <- as.data.frame(as.matrix(table(values)))
col_results <- as.data.frame(as.matrix(table(values)), stringsAsFactors = FALSE)
col_results$interpretation <- rownames(col_results)
col_results$isolates <- col_results[, 1, drop = TRUE]
if (NROW(col_results) > 0 && sum(col_results$isolates, na.rm = TRUE) > 0) {
@@ -255,19 +274,19 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
}
out_new <- cbind(group_values, out_new)
}
out <- rbind(out, out_new)
out <- rbind(out, out_new, stringsAsFactors = FALSE)
}
}
out
}
# support dplyr groups
apply_group <- function(.data, fn, groups, ...) {
grouped <- split(x = .data, f = lapply(groups, function(x, .data) as.factor(.data[, x]), .data))
# based on pm_apply_grouped_function
apply_group <- function(.data, fn, groups, drop = FALSE, ...) {
grouped <- pm_split_into_groups(.data, groups, drop)
res <- do.call(rbind, unname(lapply(grouped, fn, ...)))
if (any(groups %in% colnames(res))) {
class(res) <- c("grouped_data", class(res))
attr(res, "groups") <- groups[groups %in% colnames(res)]
res <- pm_set_groups(res, groups[groups %in% colnames(res)])
}
res
}
@@ -291,7 +310,7 @@ rsi_calc_df <- function(type, # "proportion", "count" or "both"
if (data_has_groups) {
# ordering by the groups and two more: "antibiotic" and "interpretation"
out <- ungroup(out[do.call("order", out[, seq_len(length(groups) + 2)]), ])
out <- pm_ungroup(out[do.call("order", out[, seq_len(length(groups) + 2)]), ])
} else {
out <- out[order(out$antibiotic, out$interpretation), ]
}

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' @rdname proportion
@@ -28,7 +32,6 @@ rsi_df <- function(data,
as_percent = FALSE,
combine_SI = TRUE,
combine_IR = FALSE) {
rsi_calc_df(type = "both",
data = data,
translate_ab = translate_ab,

View File

@@ -1,37 +1,42 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Skewness of the sample
#' Skewness of the Sample
#'
#' @description Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean.
#'
#' When negative: the left tail is longer; the mass of the distribution is concentrated on the right of the figure. When positive: the right tail is longer; the mass of the distribution is concentrated on the left of the figure.
#' @inheritSection lifecycle Questioning 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.
#' 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!
#' @inheritSection AMR Read more on Our Website!
#' @export
skewness <- function(x, na.rm = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
UseMethod("skewness")
}
@@ -39,24 +44,27 @@ skewness <- function(x, na.rm = FALSE) {
#' @rdname skewness
#' @export
skewness.default <- function(x, na.rm = FALSE) {
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
x <- as.vector(x)
if (na.rm == TRUE) {
x <- x[!is.na(x)]
}
n <- length(x)
(base::sum((x - base::mean(x))^3) / n) / (base::sum((x - base::mean(x)) ^ 2) / n) ^ (3 / 2)
(sum((x - mean(x))^3) / n) / (sum((x - mean(x)) ^ 2) / n) ^ (3 / 2)
}
#' @method skewness matrix
#' @rdname skewness
#' @export
skewness.matrix <- function(x, na.rm = FALSE) {
base::apply(x, 2, skewness.default, na.rm = na.rm)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
apply(x, 2, skewness.default, na.rm = na.rm)
}
#' @method skewness data.frame
#' @rdname skewness
#' @export
skewness.data.frame <- function(x, na.rm = FALSE) {
base::sapply(x, skewness.default, na.rm = na.rm)
meet_criteria(na.rm, allow_class = "logical", has_length = 1)
vapply(FUN.VALUE = double(1), x, skewness.default, na.rm = na.rm)
}

Binary file not shown.

View File

@@ -1,43 +1,51 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' Translate strings from AMR package
#' Translate Strings from 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/master/data-raw/translations.tsv>.
#' @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/master/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.).
#'
#' Currently supported languages are (besides English): `r paste(sort(gsub(";.*", "", ISOcodes::ISO_639_2[which(ISOcodes::ISO_639_2$Alpha_2 %in% unique(AMR:::translations_file$lang)), "Name"])), collapse = ", ")`. Please note that currently not all these languages have translations available for all antimicrobial agents and colloquial microorganism names.
#' Currently supported languages are: `r paste(sort(gsub(";.*", "", ISOcodes::ISO_639_2[which(ISOcodes::ISO_639_2$Alpha_2 %in% LANGUAGES_SUPPORTED), "Name"])), collapse = ", ")`. Please note that currently not 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).
#'
#' This file will be read by all functions where a translated output can be desired, like all [mo_property()] functions ([mo_name()], [mo_gramstain()], [mo_type()], etc.).
#'
#' The system language will be used at default, if that language is supported. The system language can be overwritten with `Sys.setenv(AMR_locale = yourlanguage)`.
#' @inheritSection AMR Read more on our website!
#' ## 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:
#'
#' 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
#'
#' So 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' parameter of below functions
#' # The 'language' argument of below functions
#' # will be set automatically to your system language
#' # with get_locale()
#'
@@ -65,30 +73,48 @@
#' mo_name("CoNS", language = "pt")
#' #> "Staphylococcus coagulase negativo (CoNS)"
get_locale <- function() {
if (!is.null(getOption("AMR_locale", default = NULL))) {
return(getOption("AMR_locale"))
# AMR versions 1.3.0 and prior used the environmental variable:
if (!identical("", Sys.getenv("AMR_locale"))) {
options(AMR_locale = Sys.getenv("AMR_locale"))
}
lang <- Sys.getlocale("LC_COLLATE")
# Check the locale settings for a start with one of these languages:
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 one of: ",
paste0("'", LANGUAGES_SUPPORTED, "'", collapse = ", "))
}
} else {
# we now support the LANGUAGE system variable - return it if set
if (!identical("", Sys.getenv("LANGUAGE"))) {
return(coerce_language_setting(Sys.getenv("LANGUAGE")))
}
if (!identical("", Sys.getenv("LANG"))) {
return(coerce_language_setting(Sys.getenv("LANG")))
}
}
coerce_language_setting(Sys.getlocale("LC_COLLATE"))
}
coerce_language_setting <- function(lang) {
# grepl() with ignore.case = FALSE is faster than %like%
if (grepl("^(English|en_|EN_)", lang, ignore.case = FALSE)) {
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)) {
} 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)) {
} else if (grepl("^(Dutch|Nederlands|nl_|NL_)", lang, ignore.case = FALSE, perl = TRUE)) {
"nl"
} else if (grepl("^(Spanish|Espa.+ol|es_|ES_)", lang, ignore.case = FALSE)) {
} 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)) {
} 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)) {
} 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)) {
} else if (grepl("^(Portuguese|Portugu.+s|pt_|PT_)", lang, ignore.case = FALSE, perl = TRUE)) {
"pt"
} else {
# other language -> set to English
@@ -107,10 +133,13 @@ translate_AMR <- function(from, language = get_locale(), only_unknown = FALSE) {
}
df_trans <- translations_file # internal data file
from.bak <- from
from_unique <- unique(from)
from_unique_translated <- from_unique
stop_ifnot(language %in% df_trans$lang,
stop_ifnot(language %in% LANGUAGES_SUPPORTED,
"unsupported language: '", language, "' - use one of: ",
paste0("'", sort(unique(df_trans$lang)), "'", collapse = ", "),
paste0("'", LANGUAGES_SUPPORTED, "'", collapse = ", "),
call = FALSE)
df_trans <- subset(df_trans, lang == language)
@@ -124,24 +153,25 @@ translate_AMR <- function(from, language = get_locale(), only_unknown = FALSE) {
df_trans$fixed[is.na(df_trans$fixed)] <- TRUE
# check if text to look for is in one of the patterns
any_form_in_patterns <- tryCatch(any(from %like% paste0("(", paste(df_trans$pattern, collapse = "|"), ")")),
any_form_in_patterns <- tryCatch(any(from_unique %like% paste0("(", paste(df_trans$pattern, collapse = "|"), ")")),
error = function(e) {
warning("Translation not possible. Please open an issue on GitHub (https://github.com/msberends/AMR/issues).", call. = FALSE)
warning_("Translation not possible. Please open an issue on GitHub (https://github.com/msberends/AMR/issues).", call = FALSE)
return(FALSE)
})
if (NROW(df_trans) == 0 | !any_form_in_patterns) {
return(from)
}
for (i in seq_len(nrow(df_trans))) {
from <- gsub(x = from,
pattern = df_trans$pattern[i],
replacement = df_trans$replacement[i],
fixed = df_trans$fixed[i],
ignore.case = df_trans$ignore.case[i])
}
lapply(seq_len(nrow(df_trans)),
function(i) from_unique_translated <<- gsub(pattern = df_trans$pattern[i],
replacement = df_trans$replacement[i],
x = from_unique_translated,
ignore.case = df_trans$ignore.case[i],
fixed = df_trans$fixed[i]))
# force UTF-8 for diacritics
base::enc2utf8(from)
from_unique_translated <- enc2utf8(from_unique_translated)
# a kind of left join to get all results back
from_unique_translated[match(from.bak, from_unique)]
}

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
#' WHOCC: WHO Collaborating Centre for Drug Statistics Methodology
@@ -31,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!
#' @inheritSection AMR Read more on Our Website!
#' @name WHOCC
#' @rdname WHOCC
#' @examples

98
R/zzz.R
View File

@@ -1,67 +1,77 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# set up package environment, used by numerous AMR functions
pkg_env <- new.env(hash = FALSE)
pkg_env$mo_failed <- character(0)
.onLoad <- function(libname, pkgname) {
assign(x = "MO_lookup",
value = create_MO_lookup(),
envir = asNamespace("AMR"))
# Support for tibble headers (type_sum) and tibble columns content (pillar_shaft)
# without the need to depend on other packages. This was suggested by the
# developers of the vctrs package:
# https://github.com/r-lib/vctrs/blob/05968ce8e669f73213e3e894b5f4424af4f46316/R/register-s3.R
s3_register("pillar::pillar_shaft", "ab")
s3_register("pillar::pillar_shaft", "mo")
s3_register("pillar::pillar_shaft", "rsi")
s3_register("pillar::pillar_shaft", "mic")
s3_register("pillar::pillar_shaft", "disk")
s3_register("tibble::type_sum", "ab")
s3_register("tibble::type_sum", "mo")
s3_register("tibble::type_sum", "rsi")
s3_register("tibble::type_sum", "mic")
s3_register("tibble::type_sum", "disk")
# Support for frequency tables from the cleaner package
s3_register("cleaner::freq", "mo")
s3_register("cleaner::freq", "rsi")
# Support from skim() from the skimr package
s3_register("skimr::get_skimmers", "mo")
s3_register("skimr::get_skimmers", "rsi")
s3_register("skimr::get_skimmers", "mic")
s3_register("skimr::get_skimmers", "disk")
assign(x = "MO.old_lookup",
value = create_MO.old_lookup(),
envir = asNamespace("AMR"))
# if mo source exists, fire it up (see mo_source())
try({
if (file.exists(getOption("AMR_mo_source", "~/mo_source.rds"))) {
invisible(get_mo_source())
}
}, silent = TRUE)
}
# maybe add survey later: "https://www.surveymonkey.com/r/AMR_for_R"
create_MO_lookup <- function() {
MO_lookup <- AMR::microorganisms
MO_lookup$kingdom_index <- 99
MO_lookup[which(MO_lookup$kingdom == "Bacteria" | MO_lookup$mo == "UNKNOWN"), "kingdom_index"] <- 1
MO_lookup[which(MO_lookup$kingdom == "Fungi"), "kingdom_index"] <- 2
MO_lookup[which(MO_lookup$kingdom == "Protozoa"), "kingdom_index"] <- 3
MO_lookup[which(MO_lookup$kingdom == "Archaea"), "kingdom_index"] <- 4
# 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)))
MO_lookup[MO_lookup$genus == "" | grepl("^[(]unknown ", MO_lookup$fullname), "fullname_lower"] <- tolower(trimws(MO_lookup[MO_lookup$genus == "" | grepl("^[(]unknown ", MO_lookup$fullname),
"fullname"]))
MO_lookup$fullname_lower <- gsub("[^.a-z0-9/ \\-]+", "", MO_lookup$fullname_lower)
# 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)
# 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), ]
.onAttach <- function(...) {
# show notice in 10% of cases in interactive session
if (!interactive() || stats::runif(1) > 0.1 || isTRUE(as.logical(getOption("AMR_silentstart", FALSE)))) {
return()
}
packageStartupMessage(word_wrap("Thank you for using the AMR package! ",
"If you have a minute, please anonymously fill in this short questionnaire to improve the package and its functionalities: ",
font_blue("https://msberends.github.io/AMR/survey.html\n"),
"[prevent his notice with ",
font_bold("suppressPackageStartupMessages(library(AMR))"),
" or use ",
font_bold("options(AMR_silentstart = TRUE)"), "]"))
}
create_MO.old_lookup <- function() {
MO.old_lookup <- AMR::microorganisms.old
MO.old_lookup$fullname_lower <- gsub("[^.a-z0-9/ \\-]+", "", tolower(trimws(MO.old_lookup$fullname)))
# add a column with only "e coli" like combinations
MO.old_lookup$g_species <- 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), ]
}

View File

@@ -1,21 +1,32 @@
% AMR (for R)
# `AMR` (for R)
[![CRAN](https://www.r-pkg.org/badges/version-ago/AMR)](https://cran.r-project.org/package=AMR)
[![CRANlogs](https://cranlogs.r-pkg.org/badges/grand-total/AMR)](https://cran.r-project.org/package=AMR)
![R-code-check](https://github.com/msberends/AMR/workflows/R-code-check/badge.svg?branch=master)
[![CodeFactor](https://www.codefactor.io/repository/github/msberends/amr/badge)](https://www.codefactor.io/repository/github/msberends/amr)
[![Codecov](https://codecov.io/gh/msberends/AMR/branch/master/graph/badge.svg)](https://codecov.io/gh/msberends/AMR?branch=master)
<img src="https://msberends.github.io/AMR/works_great_on.png" align="center" height="150px" />
The latest built **source package** (`AMR_x.x.x.tar.gz`) can be found in folder [/data-raw/](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.
After installing this package, R knows ~70,000 distinct microbial species and all ~550 antibiotic, antimycotic and antiviral drugs by name and code (including ATC, EARS-NET, LOINC and SNOMED CT), and knows all about valid R/SI and MIC values. It supports any data format, including WHONET/EARS-Net data.
This package is fully independent of any other R package and works on Windows, macOS and Linux with all versions of R since R-3.0.0 (April 2013). It was designed to work in any setting, including those with very limited resources. It was created for both routine data analysis and academic research at the Faculty of Medical Sciences of the University of Groningen, in collaboration with non-profit organisations Certe Medical Diagnostics and Advice and University Medical Center Groningen. This R package is actively maintained and free software; you can freely use and distribute it for both personal and commercial (but not patent) purposes under the terms of the GNU General Public License version 2.0 (GPL-2), as published by the Free Software Foundation.
This is the development source of the `AMR` package for R. Not a developer? Then please visit our website [https://msberends.github.io/AMR](https://msberends.github.io/AMR) to read more about this package.
This is the development source of the `AMR` package for R. Not a developer? Then please visit our website [https://msberends.github.io/AMR/](https://msberends.github.io/AMR/) to read more about this package.
*NOTE: this source code is on GitHub (https://github.com/msberends/AMR), but also automatically mirrored to GitLab (https://gitlab.com/msberends/AMR).*
### How to get this package
Please see [our website](https://msberends.github.io/AMR/#get-this-package).
Bottom line: `install.packages("AMR")`
### Copyright
This R package is licensed under the [GNU General Public License (GPL) v2.0](https://github.com/msberends/AMR/blob/master/LICENSE). In a nutshell, this means that this package:

View File

@@ -1,26 +1,30 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
title: "AMR (for R)"
url: "https://msberends.github.io/AMR"
url: "https://msberends.github.io/AMR/"
development:
mode: "release" # improves indexing by search engines
@@ -44,6 +48,9 @@ navbar:
- text: "Predict antimicrobial resistance"
icon: "fa-dice"
href: "articles/resistance_predict.html"
- text: "Data sets for download / own use"
icon: "fa-database"
href: "articles/datasets.html"
- text: "Conduct principal component analysis for AMR"
icon: "fa-compress"
href: "articles/PCA.html"
@@ -61,10 +68,10 @@ navbar:
href: "articles/EUCAST.html"
- text: "Get properties of a microorganism"
icon: "fa-bug"
href: "reference/mo_property.html" # reference instead of article
href: "reference/mo_property.html" # reference instead of an article
- text: "Get properties of an antibiotic"
icon: "fa-capsules"
href: "reference/ab_property.html" # reference instead of article
href: "reference/ab_property.html" # reference instead of an article
- text: "Other: benchmarks"
icon: "fa-shipping-fast"
href: "articles/benchmarks.html"
@@ -86,85 +93,105 @@ navbar:
href: "survey.html"
reference:
- title: "Cleaning your data"
desc: >
Functions for cleaning and optimising your data, to be able to add
variables later on (like taxonomic properties) or to fix and extend
antibiotic interpretations by applying [EUCAST rules](http://www.eucast.org/expert_rules_and_intrinsic_resistance/).
contents:
- starts_with("as.")
- "`eucast_rules`"
- "`ab_from_text`"
- "`guess_ab_col`"
- "`mo_source`"
- title: "Enhancing your data"
desc: >
Functions to add new data to your existing data, such as the determination
of first isolates, multi-drug resistant microorganisms (MDRO), getting
properties of microorganisms or antibiotics and determining the age of
patients or divide ages into age groups.
contents:
- "`ab_property`"
- "`age_groups`"
- "`age`"
- "`atc_online_property`"
- "`first_isolate`"
- "`join`"
- "`key_antibiotics`"
- "`mdro`"
- "`mo_property`"
- "`p_symbol`"
- title: "Analysing your data"
desc: >
Functions for conducting AMR analysis, like counting isolates, calculating
resistance or susceptibility, or make plots.
contents:
- "`proportion`"
- "`count`"
- "`availability`"
- "`bug_drug_combinations`"
- "`resistance_predict`"
- "`pca`"
- "`antibiotic_class_selectors`"
- "`filter_ab_class`"
- "`g.test`"
- "`ggplot_rsi`"
- "`ggplot_pca`"
- "`kurtosis`"
- "`skewness`"
- title: "Included data sets"
desc: >
Scientifically reliable references for microorganisms and
antibiotics, and example data sets to use for practise.
contents:
- "`microorganisms`"
- "`antibiotics`"
- "`antivirals`"
- "`example_isolates`"
- "`example_isolates_unclean`"
- "`rsi_translation`"
- "`microorganisms.codes`"
- "`microorganisms.old`"
- "`WHONET`"
- title: "Background information"
- title: "Background information on included data"
desc: >
Some pages about our package and its external sources. Be sure to read our [How To's](./../articles/index.html)
for more information about how to work with functions in this package.
contents:
- "`AMR`"
- "`example_isolates`"
- "`microorganisms`"
- "`microorganisms.codes`"
- "`microorganisms.old`"
- "`antibiotics`"
- "`intrinsic_resistant`"
- "`dosage`"
- "`catalogue_of_life`"
- "`catalogue_of_life_version`"
- "`WHOCC`"
- "`lifecycle`"
- title: "Other functions"
- "`example_isolates_unclean`"
- "`rsi_translation`"
- "`WHONET`"
- title: "Preparing data: microorganisms"
desc: >
These functions are meant to get taxonomically valid properties of microorganisms from any input.
Use `mo_source()` to teach this package how to translate your own codes to valid microorganism codes.
contents:
- "`as.mo`"
- "`mo_property`"
- "`mo_source`"
- title: "Preparing data: antibiotics"
desc: >
Use these functions to get valid properties of antibiotics from any input or to clean your input.
You can even retrieve drug names and doses from clinical text records, using `ab_from_text()`.
contents:
- "`as.ab`"
- "`ab_property`"
- "`ab_from_text`"
- "`atc_online_property`"
- title: "Preparing data: antimicrobial resistance"
desc: >
With `as.mic()` and `as.disk()` you can transform your raw input to valid MIC or disk diffusion values.
Use `as.rsi()` for cleaning raw data to let it only contain "R", "I" and "S", or to interpret MIC or disk diffusion values as R/SI based on the lastest EUCAST and CLSI guidelines.
Afterwards, you can extend antibiotic interpretations by applying [EUCAST rules](https://www.eucast.org/expert_rules_and_intrinsic_resistance/) with `eucast_rules()`.
contents:
- "`as.rsi`"
- "`as.mic`"
- "`as.disk`"
- "`eucast_rules`"
- "`plot`"
- "`isolate_identifier`"
- title: "Analysing data: antimicrobial resistance"
desc: >
Use these function for the analysis part. You can use `susceptibility()` or `resistance()` on any antibiotic column.
Be sure to first select the isolates that are appropiate for analysis, by using `first_isolate()` or `is_new_episode()`.
You can also filter your data on certain resistance in certain antibiotic classes (`filter_ab_class()`), or determine multi-drug resistant microorganisms (MDRO, `mdro()`).
contents:
- "`proportion`"
- "`count`"
- "`is_new_episode`"
- "`first_isolate`"
- "`key_antibiotics`"
- "`mdro`"
- "`count`"
- "`ggplot_rsi`"
- "`bug_drug_combinations`"
- "`antibiotic_class_selectors`"
- "`filter_ab_class`"
- "`resistance_predict`"
- "`guess_ab_col`"
- title: "Other: miscellaneous functions"
desc: >
These functions are mostly for internal use, but some of
them may also be suitable for your analysis. Especially the
'like' function can be useful: `if (x %like% y) {...}`.
contents:
- "`age_groups`"
- "`age`"
- "`availability`"
- "`get_locale`"
- "`ggplot_pca`"
- "`join`"
- "`like`"
- title: "Deprecated functions"
- "`mo_matching_score`"
- "`pca`"
- "`random`"
- title: "Other: statistical tests"
desc: >
Some statistical tests or methods are not part of base R and were added to this package for convenience.
contents:
- "`g.test`"
- "`kurtosis`"
- "`skewness`"
- title: "Other: deprecated functions"
desc: >
These functions are deprecated, meaning that they will still
work but show a warning with every use and will be removed
@@ -187,6 +214,8 @@ authors:
href: https://www.rug.nl/staff/c.glasner/
template:
# this requires the 'preferably' package, https://github.com/amirmasoudabdol/preferably/
# package: preferably
assets: "pkgdown/logos" # use logos in this folder
params:
noindex: false

View File

@@ -1,22 +1,26 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
codecov:

View File

@@ -1,3 +1 @@
* Edited the unit tests, so they will run under 10 minutes on CRAN (using testthat::skip_on_cran() on some tests).
* Since version 0.3.0 (2018-08-14), CHECK returns a NOTE for having a data directory over 3 MB. This is needed to offer users reference data for the complete taxonomy of microorganisms - one of the most important features of this package.
* Ever since one of the first CRAN releases, CHECK returns a NOTE for having a data and R directory over 3 MB. This is needed to offer users reference data for the complete taxonomy of microorganisms - one of the most important features of this package.

Binary file not shown.

Binary file not shown.

1
data-raw/ab.md5 Normal file
View File

@@ -0,0 +1 @@
fa68ab044001078f290218a7de6cc5c4

BIN
data-raw/antibiotics.dta Normal file

Binary file not shown.

BIN
data-raw/antibiotics.rds Normal file

Binary file not shown.

BIN
data-raw/antibiotics.sas Normal file

Binary file not shown.

BIN
data-raw/antibiotics.sav Normal file

Binary file not shown.

View File

@@ -7,14 +7,14 @@
"AMK" "J01GB06" 37768 "Amikacin" "Aminoglycosides" "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" "J01CA04" 33613 "Amoxicillin" "Beta-lactams/penicillins" "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 "g" 1 "g" "c(\"16365-9\", \"25274-2\", \"3344-9\", \"80133-2\")"
"AMC" "J01CR02" 23665637 "Amoxicillin/clavulanic acid" "Beta-lactams/penicillins" "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 "g" 3 "g" "character(0)"
\"piramox\", \"robamox\", \"sawamox pm\", \"tolodina\", \"unicillin\", \"utimox\", \"vetramox\")" 1.5 "g" 3 "g" "c(\"16365-9\", \"25274-2\", \"3344-9\", \"80133-2\")"
"AMC" "J01CR02" 23665637 "Amoxicillin/clavulanic acid" "Beta-lactams/penicillins" "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" "J02AA01" 5280965 "Amphotericin B" "Antifungals/antimycotics" "Antimycotics for systemic use" "Antibiotics" "c(\"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\")" 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" "J01CA01" 6249 "Ampicillin" "Beta-lactams/penicillins" "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" 2 "g" "c(\"21066-6\", \"3355-5\", \"33562-0\", \"33919-2\", \"43883-8\", \"43884-6\", \"87604-5\")"
\"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" "J01CR01" 119561 "Ampicillin/sulbactam" "Beta-lactams/penicillins" "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" "J02AX06" 166548 "Anidulafungin" "Antifungals/antimycotics" "Antimycotics for systemic use" "Other antimycotics for systemic use" "anid" "c(\"anidulafungin\", \"anidulafungina\", \"anidulafungine\", \"anidulafunginum\", \"ecalta\", \"eraxis\")" 0.1 "g" "58420-1"
@@ -37,13 +37,15 @@
"BEK" 439318 "Bekanamycin" "Aminoglycosides" "" "c(\"aminodeoxykanamycin\", \"becanamicina\", \"bekanamycin\", \"bekanamycine\", \"bekanamycinum\", \"nebramycin v\")" "character(0)"
"BNB" "J01CE08" "Benzathine benzylpenicillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "" 3.6 "g" ""
"BNP" "J01CE10" 64725 "Benzathine phenoxymethylpenicillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"bicillin v\", \"biphecillin\")" 2 "g" "character(0)"
"PEN" "J01CE01" 5904 "Benzylpenicillin" "Beta-lactams/penicillins" "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" "" "besifloxacin" "character(0)"
"BIA" 71339 "Biapenem" "Carbapenems" "" "c(\"biapenem\", \"biapenern\", \"bipenem\", \"omegacin\")" "character(0)"
"BCZ" 65807 "Bicyclomycin (Bicozamycin)" "Other antibacterials" "" "c(\"aizumycin\", \"bacfeed\", \"bacteron\", \"bicozamicina\", \"bicozamycin\", \"bicozamycine\", \"bicozamycinum\")" "character(0)"
"BDP" "J01EA02" 68760 "Brodimoprim" "Trimethoprims" "Sulfonamides and trimethoprim" "Trimethoprim and derivatives" "" "c(\"brodimoprim\", \"brodimoprima\", \"brodimoprime\", \"brodimoprimum\", \"bromdimoprim\", \"hyprim\", \"unitrim\")" 0.2 "g" "character(0)"
"BUT" 47472 "Butoconazole" "Antifungals/antimycotics" "" "c(\"butaconazole\", \"butoconazol\", \"butoconazole\", \"butoconazolum\", \"compositenstarke\", \"dahlin\", \"femstat\", \"gynofort\", \"polyfructosanum\")" "character(0)"
"CDZ" "J01DD09" 44242317 "Cadazolid" "Cephalosporins (3rd gen.)" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "" "cadazolid" 2 "g" "character(0)"
"CLA" "J04AA03" "Calcium aminosalicylate" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Aminosalicylic acid and derivatives" "" "" ""
"CLA" "J04AA03" "Calcium aminosalicylate" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Aminosalicylic acid and derivatives" "" "" 15 ""
"CAP" "J04AB30" 135565060 "Capreomycin" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Antibiotics" "c(\"\", \"capr\")" "" 1 "g" ""
"CRB" "J01CA03" 20824 "Carbenicillin" "Beta-lactams/penicillins" "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" "J01CA05" 93184 "Carindacillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"carindacilina\", \"carindacillin\", \"carindacilline\", \"carindacillinum\")" 4 "g" "character(0)"
@@ -63,7 +65,7 @@
"CDR" "J01DD15" 6915944 "Cefdinir" "Cephalosporins (3rd gen.)" "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" "J01DD16" 9870843 "Cefditoren" "Cephalosporins (3rd gen.)" "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" "J01DE01" 5479537 "Cefepime" "Cephalosporins (4th gen.)" "Other beta-lactam antibacterials" "Fourth-generation cephalosporins" "c(\"cfep\", \"cfpi\", \"cpe\", \"cpm\", \"fep\", \"pm\", \"xpm\")" "c(\"axepim\", \"cefepima\", \"cefepime\", \"cefepimum\", \"cepimax\", \"cepimex\", \"maxcef\", \"maxipime\")" 2 "g" "38363-8"
"FEP" "J01DE01" 5479537 "Cefepime" "Cephalosporins (4th gen.)" "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\")" "" ""
"FPT" 9567558 "Cefepime/tazobactam" "Cephalosporins (4th gen.)" "" "" ""
"FPZ" "Cefepime/zidebactam" "Other antibacterials" "" "" ""
@@ -100,14 +102,14 @@
"CDC" "Cefpodoxime/clavulanic acid" "Cephalosporins (3rd gen.)" "c(\"\", \"cecl\")" "" ""
"CPR" "J01DC10" 5281006 "Cefprozil" "Cephalosporins (2nd gen.)" "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" "J01DB11" 5284529 "Cefroxadine" "Cephalosporins (1st gen.)" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"cefroxadine\", \"cefroxadino\", \"cefroxadinum\")" "character(0)"
"CRD" "J01DB11" 5284529 "Cefroxadine" "Cephalosporins (1st gen.)" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"cefroxadine\", \"cefroxadino\", \"cefroxadinum\")" 2.1 "character(0)"
"CFS" "J01DD03" 656575 "Cefsulodin" "Cephalosporins (3rd gen.)" "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" "J01DI02" 56841980 "Ceftaroline" "Cephalosporins (5th gen.)" "c(\"\", \"cfro\")" "c(\"teflaro\", \"zinforo\")" "character(0)"
"CPT" "J01DI02" 56841980 "Ceftaroline" "Cephalosporins (5th gen.)" "c(\"\", \"cfro\")" "c(\"teflaro\", \"zinforo\")" 1.2 "character(0)"
"CPA" "Ceftaroline/avibactam" "Cephalosporins (5th gen.)" "" "" ""
"CAZ" "J01DD02" 5481173 "Ceftazidime" "Cephalosporins (3rd gen.)" "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" "Ceftazidime/avibactam" "Cephalosporins (3rd gen.)" "c(\"\", \"cfav\")" "" ""
"CCV" "J01DD52" 9575352 "Ceftazidime/clavulanic acid" "Cephalosporins (3rd gen.)" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"czcl\", \"xtzl\")" "" ""
"CCV" "J01DD52" 9575352 "Ceftazidime/clavulanic acid" "Cephalosporins (3rd gen.)" "Other beta-lactam antibacterials" "Third-generation cephalosporins" "c(\"czcl\", \"xtzl\")" "" 6 ""
"CEM" 6537431 "Cefteram" "Cephalosporins (3rd gen.)" "" "c(\"cefteram\", \"cefterame\", \"cefteramum\", \"ceftetrame\")" "character(0)"
"CPL" 5362114 "Cefteram pivoxil" "Cephalosporins (3rd gen.)" "" "c(\"cefteram pivoxil\", \"tomiron\")" "character(0)"
"CTL" "J01DB12" 65755 "Ceftezole" "Cephalosporins (1st gen.)" "Other beta-lactam antibacterials" "First-generation cephalosporins" "" "c(\"ceftezol\", \"ceftezole\", \"ceftezolo\", \"ceftezolum\", \"demethylcefazolin\")" 3 "g" "character(0)"
@@ -115,9 +117,9 @@
"TIO" 6328657 "Ceftiofur" "Cephalosporins (3rd gen.)" "" "c(\"ceftiofur\", \"ceftiofurum\", \"excede\", \"excenel\", \"naxcel\")" "character(0)"
"CZX" "J01DD07" 6533629 "Ceftizoxime" "Cephalosporins (3rd gen.)" "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" "J01DI01" 135413542 "Ceftobiprole" "Cephalosporins (5th gen.)" "" "ceftobiprole" "character(0)"
"CFM1" "J01DI01" 135413544 "Ceftobiprole medocaril" "Cephalosporins (5th gen.)" "Other beta-lactam antibacterials" "Other cephalosporins" "" "" ""
"CEI" "J01DI54" "Ceftolozane/enzyme inhibitor" "Cephalosporins (5th gen.)" "Other beta-lactam antibacterials" "Other cephalosporins" "" "" ""
"BPR" "J01DI01" 135413542 "Ceftobiprole" "Cephalosporins (5th gen.)" "" "ceftobiprole" 1.5 "character(0)"
"CFM1" "J01DI01" 135413544 "Ceftobiprole medocaril" "Cephalosporins (5th gen.)" "Other beta-lactam antibacterials" "Other cephalosporins" "" "" 1.5 ""
"CEI" "J01DI54" "Ceftolozane/enzyme inhibitor" "Cephalosporins (5th gen.)" "Other beta-lactam antibacterials" "Other cephalosporins" "" "" 3 ""
"CZT" "Ceftolozane/tazobactam" "Cephalosporins (5th gen.)" "" "" ""
"CRO" "J01DD04" 5479530 "Ceftriaxone" "Cephalosporins (3rd gen.)" "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" "J01DC02" 5479529 "Cefuroxime" "Cephalosporins (2nd gen.)" "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\")"
@@ -141,7 +143,7 @@
"CIX" "D01AE14" 47472 "Ciclopirox" "Antifungals/antimycotics" "Antifungals for topical use" "Other antifungals for topical use" "cipx" "c(\"butaconazole\", \"butoconazol\", \"butoconazole\", \"butoconazolum\", \"compositenstarke\", \"dahlin\", \"femstat\", \"gynofort\", \"polyfructosanum\")" "character(0)"
"CIN" "J01MB06" 2762 "Cinoxacin" "Quinolones" "Quinolone antibacterials" "Other quinolones" "c(\"cino\", \"cnox\")" "c(\"azolinic acid\", \"cinobac\", \"cinobactin\", \"cinoxacin\", \"cinoxacine\", \"cinoxacino\", \"cinoxacinum\", \"clinoxacin\", \"noxigram\", \"uronorm\")" 1 "g" "character(0)"
"CIP" "J01MA02" 2764 "Ciprofloxacin" "Quinolones" "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.5 "g" "c(\"14031-9\", \"14032-7\", \"14058-2\", \"14059-0\", \"25248-6\", \"34636-1\", \"3484-3\")"
\"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" "J01FA09" 84029 "Clarithromycin" "Macrolides/lincosamides" "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)"
@@ -154,22 +156,22 @@
"CTR" "G01AF02" 2812 "Clotrimazole" "Antifungals/antimycotics" "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" "J01CF02" 6098 "Cloxacillin" "Beta-lactams/penicillins" "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" "J01XB01" 5311054 "Colistin" "Polymyxins" "Other antibacterials" "Polymyxins" "c(\"cl\", \"coli\", \"cs\", \"ct\")" "c(\"belcomycine\", \"colimycin\", \"colimycin sulphate\", \"colisticin\", \"colistimethate\", \"colistimethate sodium\", \"colistin sulfate\", \"colistin sulphate\", \"colomycin\", \"coly-mycin\", \"polymyxin e\", \"polymyxin e. sulfate\", \"promixin\", \"totazina\")" 3 "MU" "c(\"16645-4\", \"29493-4\")"
"COL" "J01XB01" 5311054 "Colistin" "Polymyxins" "Other antibacterials" "Polymyxins" "c(\"cl\", \"coli\", \"cs\", \"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" "c(\"16645-4\", \"29493-4\")"
"COP" "Colistin/polysorbate" "Other antibacterials" "" "" ""
"CYC" "J04AB01" 6234 "Cycloserine" "Antimycobacterials" "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" "J01XA04" 23724878 "Dalbavancin" "Glycopeptides" "Other antibacterials" "Glycopeptide antibacterials" "dalb" "c(\"dalbavancin\", \"dalvance\")" "character(0)"
"CYC" "J04AB01" 6234 "Cycloserine" "Oxazolidinones" "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" "J01XA04" 23724878 "Dalbavancin" "Glycopeptides" "Other antibacterials" "Glycopeptide antibacterials" "dalb" "c(\"dalbavancin\", \"dalvance\")" 1.5 "character(0)"
"DAN" 71335 "Danofloxacin" "Quinolones" "" "c(\"advocin\", \"danofloxacin\", \"danofloxacine\", \"danofloxacino\", \"danofloxacinum\")" "character(0)"
"DPS" "J04BA02" 2955 "Dapsone" "Other antibacterials" "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" "J01XX09" 16134395 "Daptomycin" "Other antibacterials" "Other antibacterials" "Other antibacterials" "c(\"dap\", \"dapt\")" "c(\"cidecin\", \"cubicin\", \"dapcin\", \"daptomicina\", \"daptomycine\", \"daptomycinum\")" 0.28 "g" "character(0)"
"DFX" 487101 "Delafloxacin" "Quinolones" "" "c(\"baxdela\", \"delafloxacin\", \"delafloxacinum\")" "character(0)"
"DLM" "J04AK06" 6480466 "Delamanid" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "dela" "c(\"delamanid\", \"deltyba\")" "character(0)"
"DLM" "J04AK06" 6480466 "Delamanid" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "dela" "c(\"delamanid\", \"deltyba\")" 0.2 "character(0)"
"DEM" "J01AA01" 54680690 "Demeclocycline" "Tetracyclines" "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" "J01GB09" 470999 "Dibekacin" "Aminoglycosides" "Aminoglycoside antibacterials" "Other aminoglycosides" "" "c(\"debecacin\", \"dibekacin\", \"dibekacin sulfate\", \"dibekacina\", \"dibekacine\", \"dibekacinum\", \"dideoxykanamycin b\", \"kappati\", \"orbicin\", \"panamicin\")" 0.14 "g" "character(0)"
"DIC" "J01CF01" 18381 "Dicloxacillin" "Beta-lactams/penicillins" "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" "J01FA13" 6473883 "Dirithromycin" "Macrolides/lincosamides" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"dirithromycin\", \"dirithromycine\", \"dirithromycinum\", \"diritromicina\", \"divitross\", \"dynabac\", \"noriclan\", \"valodin\")" 0.5 "g" "character(0)"
"DOR" "J01DH04" 73303 "Doripenem" "Carbapenems" "Other beta-lactam antibacterials" "Carbapenems" "dori" "c(\"doribax\", \"doripenem\", \"doripenem hydrate\", \"finibax\")" "character(0)"
"DOR" "J01DH04" 73303 "Doripenem" "Carbapenems" "Other beta-lactam antibacterials" "Carbapenems" "dori" "c(\"doribax\", \"doripenem\", \"doripenem hydrate\", \"finibax\")" 1.5 "character(0)"
"DOX" "J01AA02" 54671203 "Doxycycline" "Tetracyclines" "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" "J01XDXX" 3198 "Econazole" "Antifungals/antimycotics" "econ" "c(\"econazol\", \"econazole\", \"econazolum\", \"ecostatin\", \"ecostatin cream\", \"palavale\", \"pevaryl\", \"spectazole\", \"spectazole cream\")" "character(0)"
"ENX" "J01MA04" 3229 "Enoxacin" "Quinolones" "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\")"
@@ -188,7 +190,7 @@
"ETI1" "J04AD03" 2761171 "Ethionamide" "Antimycobacterials" "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)"
"FAR" "J01DI03" 65894 "Faropenem" "Other antibacterials" "" "c(\"faropenem\", \"faropenem sodium\", \"fropenem\", \"fropenum sodium\")" "character(0)"
"FAR" "J01DI03" 65894 "Faropenem" "Other antibacterials" "" "c(\"faropenem\", \"faropenem sodium\", \"fropenem\", \"fropenum sodium\")" 0.75 "character(0)"
"FDX" 10034073 "Fidaxomicin" "Other antibacterials" "" "c(\"dificid\", \"dificlir\", \"difimicin\", \"fidaxomicin\", \"lipiarmycin\", \"tiacumicin b\")" "character(0)"
"FIN" 11567473 "Finafloxacin" "Quinolones" "" "finafloxacin" "character(0)"
"FLA" 46783781 "Flavomycin" "Other antibacterials" "" "moenomycin complex" "character(0)"
@@ -210,7 +212,7 @@
"GAM" 59364992 "Gamithromycin" "Macrolides/lincosamides" "" "gamithromycin" "character(0)"
"GRN" 124093 "Garenoxacin" "Quinolones" "" "c(\"ganefloxacin\", \"garenfloxacin\", \"garenoxacin\")" "character(0)"
"GAT" "J01MA16" 5379 "Gatifloxacin" "Quinolones" "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" "J01MA15" 9571107 "Gemifloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"factiv\", \"factive\", \"gemifioxacin\", \"gemifloxacin\", \"gemifloxacine\", \"gemifloxacino\", \"gemifloxacinum\")" "character(0)"
"GEM" "J01MA15" 9571107 "Gemifloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"factiv\", \"factive\", \"gemifioxacin\", \"gemifloxacin\", \"gemifloxacine\", \"gemifloxacino\", \"gemifloxacinum\")" 0.32 "character(0)"
"GEN" "J01GB03" 3467 "Gentamicin" "Aminoglycosides" "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(\"gehl\", \"genta high\", \"gentamicin high\")" "" ""
"GEP" 25101874 "Gepotidacin" "Other antibacterials" "" "gepotidacin" "character(0)"
@@ -248,16 +250,16 @@
"LND" 9850038 "Levonadifloxacin" "Quinolones" "" "levonadifloxacin" "character(0)"
"LSP" "Linco-spectin (lincomycin/spectinomycin)" "Other antibacterials" "" "" ""
"LIN" "J01FF02" 3000540 "Lincomycin" "Macrolides/lincosamides" "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" "J01XX08" 441401 "Linezolid" "Other antibacterials" "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\")"
"LNZ" "J01XX08" 441401 "Linezolid" "Oxazolidinones" "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" "J01MA07" 3948 "Lomefloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "c(\"lmf\", \"lom\", \"lome\")" "c(\"lomefloxacin\", \"lomefloxacine\", \"lomefloxacino\", \"lomefloxacinum\", \"maxaquin\")" "character(0)"
"LOM" "J01MA07" 3948 "Lomefloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "c(\"lmf\", \"lom\", \"lome\")" "c(\"lomefloxacin\", \"lomefloxacine\", \"lomefloxacino\", \"lomefloxacinum\", \"maxaquin\")" 0.4 "character(0)"
"LOR" "J01DC08" 5284585 "Loracarbef" "Cephalosporins (2nd gen.)" "Other beta-lactam antibacterials" "Second-generation cephalosporins" "c(\"\", \"lora\")" "c(\"anhydrous loracarbef\", \"lorabid\", \"loracarbef\", \"loracarbefum\", \"lorbef\", \"loribid\")" 0.6 "g" "character(0)"
"LYM" "J01AA04" 54707177 "Lymecycline" "Tetracyclines" "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" "J01XX06" 1292 "Mandelic acid" "Other antibacterials" "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)"
"MAR" 60651 "Marbofloxacin" "Quinolones" "" "c(\"marbocyl\", \"marbofloxacin\", \"marbofloxacine\", \"marbofloxacino\", \"marbofloxacinum\", \"zeniquin\")" "character(0)"
"MEC" "J01CA11" 36273 "Mecillinam (Amdinocillin)" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "" "c(\"amdinocillin\", \"coactin\", \"hexacillin\", \"mecilinamo\", \"mecillinam\", \"mecillinamum\", \"micillinam\", \"penicillin hx\", \"selexidin\")" 1.2 "g" "character(0)"
"MEL" 71306732 "Meleumycin" "Macrolides/lincosamides" "" "" ""
"MEM" "J01DH02" 441130 "Meropenem" "Carbapenems" "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\")" 2 "g" "41406-0"
"MEM" "J01DH02" 441130 "Meropenem" "Carbapenems" "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" "J01DH52" "Meropenem/vaborbactam" "Carbapenems" "Other beta-lactam antibacterials" "Carbapenems" "" "" ""
"MES" 176886 "Mesulfamide" "Other antibacterials" "" "c(\"mesulfamide\", \"mesulfamido\", \"mesulfamidum\")" "character(0)"
@@ -277,7 +279,7 @@
"MIF" "J02AX05" 477468 "Micafungin" "Antifungals/antimycotics" "Antimycotics for systemic use" "Other antimycotics for systemic use" "c(\"\", \"mica\")" "c(\"micafungin\", \"mycamine\")" 0.1 "g" "58418-5"
"MCZ" "J02AB01" 4189 "Miconazole" "Antifungals/antimycotics" "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\")" 1 "g" "17278-3"
"MCR" 3037206 "Micronomicin" "Aminoglycosides" "" "c(\"gentamicin c\", \"micromycin\", \"micronomicin\", \"micronomicina\", \"micronomicine\", \"micronomicinum\", \"sagamicin\", \"santemycin\")" "character(0)"
"MID" "J01FA03" 5282169 "Midecamycin" "Macrolides/lincosamides" "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 "g" "character(0)"
"MID" "J01FA03" 5282169 "Midecamycin" "Macrolides/lincosamides" "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 1 "g" "character(0)"
"MIL" 37614 "Miloxacin" "Quinolones" "" "c(\"miloxacin\", \"miloxacine\", \"miloxacino\", \"miloxacinum\")" "character(0)"
"MNO" "J01AA08" 54675783 "Minocycline" "Tetracyclines" "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\")" 0.2 "g" 0.2 "g" "c(\"34606-4\", \"3822-4\", \"49757-8\")"
"MCM" "J01FA11" 5282188 "Miocamycin" "Macrolides/lincosamides" "Macrolides, lincosamides and streptogramins" "Macrolides" "" "c(\"acecamycin\", \"macroral\", \"midecamycin acetate\", \"miocamen\", \"miocamycine\", \"miokamycin\", \"myocamicin\", \"ponsinomycin\")" 1.2 "g" "character(0)"
@@ -328,9 +330,6 @@
"PAZ" "J01MA18" 65957 "Pazufloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "" "c(\"pazufloxacin\", \"pazufloxacine\", \"pazufloxacino\", \"pazufloxacinum\")" 1 "g" "character(0)"
"PEF" "J01MA03" 51081 "Pefloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"pefl\")" "c(\"abactal\", \"labocton\", \"pefloxacin\", \"pefloxacine\", \"pefloxacino\", \"pefloxacinum\", \"perfloxacin\", \"silver pefloxacin\")" 0.8 "g" 0.8 "g" "3906-5"
"PNM" "J01CE06" 10250769 "Penamecillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "" "c(\"hydroxymethyl\", \"penamecilina\", \"penamecillin\", \"penamecillina\", \"penamecilline\", \"penamecillinum\")" 1.05 "g" "character(0)"
"PEN" "J01CE01" 5904 "Penicillin G" "Beta-lactams/penicillins" "Combinations of antibacterials" "Combinations of antibacterials" "c(\"p\", \"pen\", \"peni\", \"pv\")" "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"
"PNV" "J01CE01" 6869 "Penicillin V" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "c(\"bepe\", \"p\", \"pen\", \"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\")" 3.6 "g" "3914-9"
"PNO" "Penicillin/novobiocin" "Beta-lactams/penicillins" "" "" ""
"PSU" "Penicillin/sulbactam" "Beta-lactams/penicillins" "" "" ""
"PNM1" "J01AA10" 54686187 "Penimepicycline" "Tetracyclines" "Tetracyclines" "Tetracyclines" "" "c(\"duamine\", \"hydrocycline\", \"penetracyne\", \"penimepiciclina\", \"penimepicycline\", \"penimepicyclinum\")" "character(0)"
@@ -338,12 +337,12 @@
"PTZ" 55250256 "Pentizidone" "Other antibacterials" "" "" ""
"PEX" 16132253 "Pexiganan" "Other antibacterials" "" "pexiganan" "character(0)"
"PHE" "J01CE05" 272833 "Phenethicillin" "Beta-lactams/penicillins" "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" "J01CE02" 6869 "Phenoxymethylpenicillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase sensitive penicillins" "c(\"\", \"fepe\")" "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)"
"PHN" "J01CE02" 6869 "Phenoxymethylpenicillin" "Beta-lactams/penicillins" "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 (Natamycin)" "Antifungals/antimycotics" "" "c(\"delvocid\", \"mycophyt\", \"myprozine\", \"natacyn\", \"natamicina\", \"natamycin\", \"natamycine\", \"natamycinum\", \"pimafucin\", \"pimaracin\", \"pimarizin\", \"synogil\", \"tennecetin\")" "character(0)"
"PPA" "J01MB04" 4831 "Pipemidic acid" "Quinolones" "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" "J01CA12" 43672 "Piperacillin" "Beta-lactams/penicillins" "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" "J01CR05" 461573 "Piperacillin/tazobactam" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"p/t\", \"piptaz\", \"pita\", \"pt\", \"ptc\", \"ptz\", \"tzp\")" "c(\"\", \"tazocel\", \"tazocillin\", \"tazocin\", \"zosyn\")" 14 "g" "character(0)"
"TZP" "J01CR05" 461573 "Piperacillin/tazobactam" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Combinations of penicillins, incl. beta-lactamase inhibitors" "c(\"p/t\", \"piptaz\", \"piptazo\", \"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" "Other antibacterials" "" "c(\"pirlimycin\", \"pirlimycina\", \"pirlimycine\", \"pirlimycinum\", \"pirsue\")" "character(0)"
"PIR" "J01MB03" 4855 "Piromidic acid" "Quinolones" "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)"
@@ -355,6 +354,7 @@
"POS" "J02AC04" 468595 "Posaconazole" "Antifungals/antimycotics" "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" "J04AK08" 456199 "Pretomanid" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "" "" ""
"PRM" 6446787 "Primycin" "Macrolides/lincosamides" "" "" ""
"PRI" "J01FG01" 11979535 "Pristinamycin" "Macrolides/lincosamides" "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" "J01CE09" 5903 "Procaine benzylpenicillin" "Beta-lactams/penicillins" "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)"
@@ -369,7 +369,7 @@
"RAM" 16132338 "Ramoplanin" "Glycopeptides" "" "ramoplanin" "character(0)"
"RZM" 10993211 "Razupenem" "Carbapenems" "" "razupenem" "character(0)"
"RTP" "A07AA11" 6918462 "Retapamulin" "Other antibacterials" "Intestinal antiinfectives" "Antibiotics" "" "c(\"altabax\", \"altargo\", \"retapamulin\")" 0.6 "g" "character(0)"
"RBC" "J02AC05" 44631912 "Ribociclib" "Antifungals/antimycotics" "Antimycotics for systemic use" "Triazole derivatives" "ribo" "c(\"kisqali\", \"ribociclib\")" "character(0)"
"RBC" "J02AC05" 44631912 "Ribociclib" "Antifungals/antimycotics" "Antimycotics for systemic use" "Triazole derivatives" "ribo" "c(\"kisqali\", \"ribociclib\")" 0.2 0.2 "character(0)"
"RST" "J01GB10" 33042 "Ribostamycin" "Aminoglycosides" "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" "J04AB04" 135398743 "Rifabutin" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Antibiotics" "rifb" "c(\"alfacid\", \"ansamicin\", \"ansamycin\", \"ansatipin\", \"ansatipine\", \"mycobutin\", \"rifabutin\", \"rifabutina\", \"rifabutine\", \"rifabutinum\")" 0.15 "g" "24032-5"
@@ -392,7 +392,7 @@
"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" "" "c(\"flagentyl\", \"secnidal\", \"secnidazol\", \"secnidazole\", \"secnidazolum\", \"secnil\", \"sindose\", \"solosec\")" "character(0)"
"SMF" "J04AK05" "Simvastatin/fenofibrate" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "simv" "" ""
"SMF" "J04AK05" "Simvastatin/fenofibrate" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "simv" "" 86 ""
"SIS" "J01GB08" 36119 "Sisomicin" "Aminoglycosides" "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" "" "c(\"gracevit\", \"sitafloxacinisomer\")" "character(0)"
"SDA" "J04AA02" 2724368 "Sodium aminosalicylate" "Antimycobacterials" "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)"
@@ -458,13 +458,13 @@
"TLP" 163307 "Talmetoprim" "Other antibacterials" "" "talmetoprim" "character(0)"
"TAZ" "J01CG02" 123630 "Tazobactam" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Beta-lactamase inhibitors" "tazo" "c(\"tazobactam\", \"tazobactam acid\", \"tazobactamum\", \"tazobactum\")" "character(0)"
"TBP" 9800194 "Tebipenem" "Carbapenems" "" "" ""
"TZD" "J01XX11" 11234049 "Tedizolid" "Other antibacterials" "Other antibacterials" "Other antibacterials" "tedi" "c(\"tedizolid\", \"torezolid\")" "character(0)"
"TZD" "J01XX11" 11234049 "Tedizolid" "Oxazolidinones" "Other antibacterials" "Other antibacterials" "tedi" "c(\"tedizolid\", \"torezolid\")" 0.2 0.2 "character(0)"
"TEC" "J01XA02" 16131923 "Teicoplanin" "Glycopeptides" "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" "J01XA03" 3081362 "Telavancin" "Glycopeptides" "Other antibacterials" "Glycopeptide antibacterials" "tela" "c(\"telavancin\", \"vibativ\")" "character(0)"
"TLT" "J01FA15" 3002190 "Telithromycin" "Macrolides/lincosamides" "Macrolides, lincosamides and streptogramins" "Macrolides" "c(\"\", \"teli\")" "levviax" 0.8 "g" "character(0)"
"TMX" "J01MA05" 60021 "Temafloxacin" "Quinolones" "Quinolone antibacterials" "Fluoroquinolones" "c(\"\", \"tema\")" "c(\"omniflox\", \"temafloxacin\", \"temafloxacina\", \"temafloxacine\", \"temafloxacinum\")" 0.8 "g" "character(0)"
"TEM" "J01CA17" 171758 "Temocillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"\", \"temo\")" "c(\"temocilina\", \"temocillin\", \"temocillina\", \"temocilline\", \"temocillinum\")" 2 "g" "character(0)"
"TEM" "J01CA17" 171758 "Temocillin" "Beta-lactams/penicillins" "Beta-lactam antibacterials, penicillins" "Penicillins with extended spectrum" "c(\"\", \"temo\")" "c(\"temocilina\", \"temocillin\", \"temocillina\", \"temocilline\", \"temocillinum\")" 4 "g" "character(0)"
"TRB" "D01BA02" 1549008 "Terbinafine" "Antifungals/antimycotics" "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" "" "c(\"fungistat\", \"panlomyc\", \"terazol\", \"terconazol\", \"terconazole\", \"terconazolum\", \"tercospor\", \"triaconazole\", \"zazole\")" "character(0)"
"TRZ" "J04AK03" 65720 "Terizidone" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Other drugs for treatment of tuberculosis" "" "c(\"terivalidin\", \"terizidon\", \"terizidona\", \"terizidone\", \"terizidonum\")" "character(0)"
@@ -472,7 +472,7 @@
\"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" "Antimycobacterials" "" "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\",
"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" "J01BA02" 27200 "Thiamphenicol" "Amphenicols" "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" "J04AM04" "Thioacetazone/isoniazid" "Antimycobacterials" "Drugs for treatment of tuberculosis" "Combinations of drugs for treatment of tuberculosis" "" "" ""

BIN
data-raw/antibiotics.xlsx Normal file

Binary file not shown.

BIN
data-raw/antivirals.dta Normal file

Binary file not shown.

BIN
data-raw/antivirals.rds Normal file

Binary file not shown.

BIN
data-raw/antivirals.sas Normal file

Binary file not shown.

BIN
data-raw/antivirals.sav Normal file

Binary file not shown.

View File

@@ -1,103 +1,103 @@
"atc" "cid" "name" "atc_group" "synonyms" "oral_ddd" "oral_units" "iv_ddd" "iv_units"
"J05AF06" "441300" "abacavir" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Abacavir\", \"Abacavir sulfate\", \"Ziagen\")" "0.6" "g"
"J05AB01" "135398513" "aciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Acicloftal\", \"Aciclovier\", \"Aciclovir\", \"Aciclovirum\", \"Activir\", \"AcycloFoam\", \"Acycloguanosine\", \"Acyclovir\", \"Acyclovir Lauriad\", \"ACYCLOVIR SODIUM\", \"Avirax\", \"Cargosil\", \"Cyclovir\", \"Genvir\", \"Gerpevir\", \"Hascovir\", \"Herpevir\", \"Maynar\", \"Poviral\", \"Sitavig\", \"Sitavir\", \"Vipral\", \"Virolex\", \"Viropump\", \"Virorax\", \"Zovirax\", \"Zovirax topical\", \"Zyclir\")" "4" "g" "4" "g"
"J05AF08" "60871" "adefovir dipivoxil" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Adefovir di ester\", \"Adefovir dipivoxil\", \"Adefovir Dipivoxil\", \"Adefovir dipivoxyl\", \"Adefovir pivoxil\", \"Adefovirdipivoxl\", \"Bisadenine\", \"BISADENINE\", \"BisPMEA\", \"Hepsera\", \"Preveon\", \"YouHeDing\")" "10" "mg"
"J05AE05" "65016" "amprenavir" "Protease inhibitors" "c(\"Agenerase\", \"Amprenavir\", \"Amprenavirum\", \"Prozei\", \"Vertex\")" "1.2" "g"
"J05AP06" "16076883" "asunaprevir" "Antivirals for treatment of HCV infections" "c(\"Asunaprevir\", \"Sunvepra\")"
"J05AE08" "148192" "atazanavir" "Protease inhibitors" "c(\"Atazanavir\", \"Atazanavir Base\", \"Latazanavir\", \"Reyataz\", \"Zrivada\")" "0.3" "g"
"J05AR15" "86583336" "atazanavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR23" "atazanavir and ritonavir" "Antivirals for treatment of HIV infections, combinations" "" "0.3" "g"
"J05AP03" "10324367" "boceprevir" "Antivirals for treatment of HCV infections" "c(\"Bocepravir\", \"Boceprevir\", \"Victrelis\")" "2.4" "g"
"J05AB15" "446727" "brivudine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Bridic\", \"Brivox\", \"Brivudin\", \"Brivudina\", \"Brivudine\", \"Brivudinum\", \"BrVdUrd\", \"Helpin\", \"Zerpex\", \"Zostex\")" "0.125" "g"
"J05AB12" "60613" "cidofovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Cidofovir\", \"Cidofovir anhydrous\", \"Cidofovir gel\", \"Cidofovirum\", \"Forvade\", \"Vistide\")" "25" "mg"
"J05AF12" "73115" "clevudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Clevudine\", \"Levovir\", \"Revovir\")" "30" "mg"
"J05AP07" "25154714" "daclatasvir" "Antivirals for treatment of HCV infections" "c(\"Daclatasvir\", \"Daklinza\")" "60" "mg"
"J05AE10" "213039" "darunavir" "Protease inhibitors" "c(\"Darunavir\", \"Darunavirum\", \"Prezista\", \"Prezista Naive\")" "1.2" "g"
"J05AR14" "darunavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AP09" "56640146" "dasabuvir" "Antivirals for treatment of HCV infections" "Dasabuvir" "0.5" "g"
"J05AP52" "dasabuvir, ombitasvir, paritaprevir and ritonavir" "Antivirals for treatment of HCV infections" ""
"J05AG02" "5625" "delavirdine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"BHAP der\", \"Delavirdin\", \"Delavirdina\", \"Delavirdine\", \"Delavirdinum\", \"PIPERAZINE\", \"Rescriptor\")" "1.2" "g"
"J05AF02" "135398739" "didanosine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Didanosina\", \"Didanosine\", \"Didanosinum\", \"Dideoxyinosine\", \"DIDEOXYINOSINE\", \"Hypoxanthine ddN\", \"Videx\", \"Videx EC\")" "0.4" "g"
"J05AX12" "54726191" "dolutegravir" "Other antivirals" "c(\"Dolutegravir\", \"Dolutegravir Sodium\", \"Soltegravir\", \"Tivicay\")" "50" "mg"
"J05AR21" "131801472" "dolutegravir and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AG06" "58460047" "doravirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Doravirine\", \"Pifeltro\")"
"J05AG03" "64139" "efavirenz" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Efavirenz\", \"Efavirenzum\", \"Eravirenz\", \"Stocrin\", \"Strocin\", \"Sustiva\")" "0.6" "g"
"J05AP54" "91669168" "elbasvir and grazoprevir" "Antivirals for treatment of HCV infections" ""
"J05AX11" "5277135" "elvitegravir" "Other antivirals" "c(\"Elvitegravir\", \"Vitekta\")"
"J05AF09" "60877" "emtricitabine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Coviracil\", \"Emtricitabin\", \"Emtricitabina\", \"Emtricitabine\", \"Emtricitabinum\", \"Emtritabine\", \"Emtriva\", \"Racivir\")" "0.2" "g"
"J05AR17" "90469070" "emtricitabine and tenofovir alafenamide" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR20" "emtricitabine, tenofovir alafenamide and bictegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR19" "emtricitabine, tenofovir alafenamide and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR22" "emtricitabine, tenofovir alafenamide, darunavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR18" "emtricitabine, tenofovir alafenamide, elvitegravir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR06" "emtricitabine, tenofovir disoproxil and efavirenz" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR08" "emtricitabine, tenofovir disoproxil and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR09" "emtricitabine, tenofovir disoproxil, elvitegravir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX07" "16130199" "enfuvirtide" "Other antivirals" "c(\"Enfurvitide\", \"Enfuvirtide\", \"Fuzeon\", \"Pentafuside\")" "0.18" "g"
"J05AX17" "10089466" "enisamium iodide" "Other antivirals" "Enisamium iodide" "1.5" "g"
"J05AF10" "135398508" "entecavir" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Baraclude\", \"Entecavir\", \"Entecavir anhydrous\", \"Entecavirum\")" "0.5" "mg"
"J05AG04" "193962" "etravirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"DAPY deriv\", \"Etravine\", \"Etravirine\", \"Intelence\")" "0.4" "g"
"J05AP04" "42601552" "faldaprevir" "Antivirals for treatment of HCV infections" "Faldaprevir"
"J05AB09" "3324" "famciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Famciclovir\", \"Famciclovirum\", \"Famvir\", \"Oravir\")" "0.75" "g"
"J05AE07" "131536" "fosamprenavir" "Protease inhibitors" "c(\"Amprenavir phosphate\", \"Fosamprenavir\", \"Lexiva\", \"Telzir\")" "1.4" "g"
"J05AD01" "3415" "foscarnet" "Phosphonic acid derivatives" "c(\"Forscarnet\", \"Forscarnet sodium\", \"Foscarmet\", \"Foscarnet\", \"Phosphonoformate\", \"Phosphonoformic acid\")" "6.5" "g"
"J05AD02" "546" "fosfonet" "Phosphonic acid derivatives" "c(\"Fosfonet\", \"Fosfonet sodium\", \"Fosfonet Sodium\", \"Fosfonoacetate\", \"Fosfonoacetic acid\", \"Phosphonacetate\", \"Phosphonacetic acid\")"
"J05AB06" "135398740" "ganciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Citovirax\", \"Cymevan\", \"Cymeven\", \"Cymevene\", \"Cytovene\", \"Cytovene IV\", \"Ganciclovir\", \"Ganciclovirum\", \"Gancyclovir\", \"Hydroxyacyclovir\", \"Virgan\", \"Vitrasert\", \"Zirgan\")" "3" "g" "0.5" "g"
"J05AP57" "glecaprevir and pibrentasvir" "Antivirals for treatment of HCV infections" ""
"J05AX23" "ibalizumab" "Other antivirals" ""
"J05AB02" "5905" "idoxuridine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Antizona\", \"Dendrid\", \"Emanil\", \"Heratil\", \"Herpesil\", \"Herpid\", \"Herpidu\", \"Herplex\", \"HERPLEX\", \"Herplex liquifilm\", \"Idexur\", \"Idossuridina\", \"Idoxene\", \"Idoxuridin\", \"Idoxuridina\", \"Idoxuridine\", \"Idoxuridinum\", \"Idu Oculos\", \"Iducher\", \"Idulea\", \"Iduoculos\", \"Iduridin\", \"Iduviran\", \"Iododeoxyridine\", \"Iododeoxyuridine\", \"Iodoxuridine\", \"Joddeoxiuridin\", \"Kerecid\", \"Kerecide\", \"Ophthalmadine\", \"Spectanefran\", \"Stoxil\", \"Synmiol\", \"Virudox\")"
"J05AE02" "5362440" "indinavir" "Protease inhibitors" "c(\"Compound J\", \"Crixivan\", \"Indinavir\", \"Indinavir anhydrous\", \"Propolis+Indinavir\")" "2.4" "g"
"J05AX05" "135449284" "inosine pranobex" "Other antivirals" "c(\"Aviral\", \"Delimmun\", \"Immunovir\", \"Imunovir\", \"Inosine pranobex\", \"Inosiplex\", \"Isoprinosin\", \"Isoprinosina\", \"Isoprinosine\", \"Isoviral\", \"Methisoprinol\", \"Methysoprinol\", \"Metisoprinol\", \"Viruxan\")" "3" "g"
"J05AF05" "60825" "lamivudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Epivir\", \"Hepitec\", \"Heptivir\", \"Heptodin\", \"Heptovir\", \"Lamivir\", \"Lamivudin\", \"Lamivudina\", \"Lamivudine\", \"Lamivudinum\", \"Zeffix\")" "0.3" "g"
"J05AR02" "lamivudine and abacavir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR16" "73386700" "lamivudine and raltegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR12" "lamivudine and tenofovir disoproxil" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR13" "lamivudine, abacavir and dolutegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR24" "lamivudine, tenofovir disoproxil and doravirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR11" "lamivudine, tenofovir disoproxil and efavirenz" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX18" "45138674" "letermovir" "Other antivirals" "c(\"Letermovir\", \"Prevymis\")" "0.48" "g" "0.48" "g"
"J05AR10" "11979606" "lopinavir and ritonavir" "Antivirals for treatment of HIV infections, combinations" "c(\"Aluvia\", \"Kaletra\")" "0.8" "g"
"J05AX02" "24839946" "lysozyme" "Other antivirals" "c(\"Lysozyme chloride\", \"Lysozyme Chloride\", \"Lysozyme G\")"
"J05AX09" "3002977" "maraviroc" "Other antivirals" "c(\"Celsentri\", \"Maraviroc\", \"Selzentry\")" "0.6" "g"
"J05AX10" "471161" "maribavir" "Other antivirals" "c(\"Benzimidavir\", \"Camvia\", \"Maribavir\")"
"J05AA01" "667492" "metisazone" "Thiosemicarbazones" "c(\"Kemoviran\", \"Marboran\", \"Marborane\", \"Methisazon\", \"Methisazone\", \"Methsazone\", \"Metisazon\", \"Metisazona\", \"Metisazone\", \"Metisazonum\", \"Viruzona\")"
"J05AX01" "71655" "moroxydine" "Other antivirals" "c(\"Bimolin\", \"Flumidine\", \"Influmine\", \"Moroxidina\", \"Moroxydine\", \"Moroxydinum\", \"Vironil\", \"Virugon\", \"Virumin\", \"Wirumin\")" "0.3" "g"
"J05AE04" "64143" "nelfinavir" "Protease inhibitors" "c(\"Nelfinavir\", \"Viracept\")" "2.25" "g"
"J05AG01" "4463" "nevirapine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Nevirapine\", \"Nevirapine anhydrous\", \"Viramune\", \"Viramune IR\", \"Viramune XR\")" "0.4" "g"
"J05AP53" "ombitasvir, paritaprevir and ritonavir" "Antivirals for treatment of HCV infections" ""
"J05AH02" "65028" "oseltamivir" "Neuraminidase inhibitors" "c(\"Agucort\", \"Oseltamivir\", \"Tamiflu\", \"Tamvir\")" "0.15" "g"
"J05AB13" "135398748" "penciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Adenovir\", \"Denavir\", \"Penciceovir\", \"Penciclovir\", \"Penciclovirum\", \"Pencyclovir\", \"Vectavir\")"
"J05AX21" "9942657" "pentanedioic acid imidazolyl ethanamide" "Other antivirals" "Ingamine" "90" "mg"
"J05AH03" "154234" "peramivir" "Neuraminidase inhibitors" "c(\"PeramiFlu\", \"Peramivir\", \"Rapiacta\", \"RAPIVAB\")"
"J05AX06" "1684" "pleconaril" "Other antivirals" "c(\"Picovir\", \"Pleconaril\", \"Pleconarilis\")"
"J05AX08" "54671008" "raltegravir" "Other antivirals" "c(\"Isentress\", \"Raltegravir\")" "0.8" "g"
"J05AP01" "37542" "ribavirin" "Antivirals for treatment of HCV infections" "c(\"Copegus\", \"Cotronak\", \"Drug: Ribavirin\", \"Ravanex\", \"Rebetol\", \"Rebetron\", \"Rebretron\", \"Ribacine\", \"Ribamide\", \"Ribamidil\", \"Ribamidyl\", \"Ribasphere\", \"Ribavirin\", \"Ribavirin Capsules\", \"Ribavirina\", \"Ribavirine\", \"Ribavirinum\", \"Ribovirin\", \"Tribavirin\", \"Varazid\", \"Vilona\", \"Viramid\", \"Viramide\", \"Virazid\", \"Virazide\", \"Virazole\")" "1" "g"
"J05AG05" "6451164" "rilpivirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Edurant\", \"Rilpivirine\")" "25" "mg"
"J05AC02" "5071" "rimantadine" "Cyclic amines" "c(\"Remantadine\", \"Riamantadine\", \"Rimant\", \"RIMANTADIN\", \"Rimantadin A\", \"Rimantadina\", \"Rimantadine\", \"Rimantadinum\")" "0.2" "g"
"J05AE03" "392622" "ritonavir" "Protease inhibitors" "c(\"Norvir\", \"Norvir Sec\", \"Norvir Softgel\", \"Ritonavir\", \"Ritonavire\", \"Ritonavirum\")" "1.2" "g"
"J05AE01" "441243" "saquinavir" "Protease inhibitors" "c(\"Fortovase\", \"Invirase\", \"Saquinavir\")" "1.8" "g"
"J05AP05" "24873435" "simeprevir" "Antivirals for treatment of HCV infections" "c(\"Olysio\", \"Simeprevir sodium\")" "0.15" "g"
"J05AP08" "45375808" "sofosbuvir" "Antivirals for treatment of HCV infections" "c(\"Hepcinat\", \"Hepcvir\", \"Sofosbuvir\", \"Sovaldi\", \"SOVALDI\", \"SoviHep\")" "0.4" "g"
"J05AP51" "72734365" "sofosbuvir and ledipasvir" "Antivirals for treatment of HCV infections" ""
"J05AP55" "91885554" "sofosbuvir and velpatasvir" "Antivirals for treatment of HCV infections" "Epclusa Tablet"
"J05AP56" "sofosbuvir, velpatasvir and voxilaprevir" "Antivirals for treatment of HCV infections" ""
"J05AF04" "18283" "stavudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Estavudina\", \"Sanilvudine\", \"Stavudin\", \"Stavudine\", \"Stavudinum\", \"Zerit Xr\", \"Zerut XR\")" "80" "mg"
"J05AR07" "15979285" "stavudine, lamivudine and nevirapine" "Antivirals for treatment of HIV infections, combinations" "STAVUDIINE"
"J05AP02" "3010818" "telaprevir" "Antivirals for treatment of HCV infections" "c(\"Incivek\", \"Incivo\", \"Telaprevir\", \"Telavic\")" "2.25" "g"
"J05AF11" "159269" "telbivudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Epavudine\", \"Sebivo\", \"Telbivudin\", \"Telbivudine\", \"Tyzeka\")" "0.6" "g"
"J05AF13" "9574768" "tenofovir alafenamide" "Nucleoside and nucleotide reverse transcriptase inhibitors" "Vemlidy" "25" "mg"
"J05AF07" "5481350" "tenofovir disoproxil" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"BisPMPA\", \"PMPA prodrug\", \"Tenofovir\", \"Viread\")" "0.245" "g"
"J05AR03" "tenofovir disoproxil and emtricitabine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX19" "5475" "tilorone" "Other antivirals" "c(\"Amiksin\", \"Amixin\", \"Amixin IC\", \"Amyxin\", \"Tiloron\", \"Tilorona\", \"Tilorone\", \"Tiloronum\")" "0.125" "g"
"J05AE09" "54682461" "tipranavir" "Protease inhibitors" "c(\"Aptivus\", \"Tipranavir\")" "1" "g"
"J05AC03" "64377" "tromantadine" "Cyclic amines" "c(\"Tromantadina\", \"Tromantadine\", \"Tromantadinum\", \"Viruserol\")"
"J05AX13" "131411" "umifenovir" "Other antivirals" "c(\"Arbidol\", \"Arbidol base\", \"Umifenovir\")" "0.8" "g"
"J05AB11" "135398742" "valaciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Talavir\", \"Valaciclovir\", \"Valaciclovirum\", \"ValACV\", \"Valcivir\", \"Valcyclovir\", \"Valtrex\", \"Virval\", \"Zelitrex\")" "3" "g"
"J05AB14" "135413535" "valganciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Cymeval\", \"Valganciclovir\")" "0.9" "g"
"J05AB03" "21704" "vidarabine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Adenine arabinoside\", \"Araadenosine\", \"Arabinoside adenine\", \"Arabinosyl adenine\", \"Arabinosyladenine\", \"Spongoadenosine\", \"Vidarabin\", \"Vidarabina\", \"Vidarabine\", \"Vidarabine anhydrous\", \"Vidarabinum\", \"Vira A\", \"Vira ATM\")"
"J05AF03" "24066" "zalcitabine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Dideoxycytidine\", \"Interferon AD + ddC\", \"Zalcitabine\", \"Zalcitibine\")" "2.25" "mg"
"J05AH01" "60855" "zanamivir" "Neuraminidase inhibitors" "c(\"MODIFIED SIALIC ACID\", \"Relenza\", \"Zanamavir\", \"Zanamir\", \"Zanamivi\", \"Zanamivir\", \"Zanamivir hydrate\")"
"J05AF01" "35370" "zidovudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Azidothymidine\", \"AZT Antiviral\", \"Beta interferon\", \"Compound S\", \"Propolis+AZT\", \"Retrovir\", \"Zidovudina\", \"Zidovudine\", \"ZIDOVUDINE\", \"Zidovudine EP III\", \"Zidovudinum\")" "0.6" "g" "0.6" "g"
"J05AR01" "zidovudine and lamivudine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR04" "zidovudine, lamivudine and abacavir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR05" "zidovudine, lamivudine and nevirapine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AF06" 441300 "Abacavir" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Abacavir\", \"Abacavir sulfate\", \"Ziagen\")" 0.6 "g"
"J05AB01" 135398513 "Aciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Acicloftal\", \"Aciclovier\", \"Aciclovir\", \"Aciclovirum\", \"Activir\", \"AcycloFoam\", \"Acycloguanosine\", \"Acyclovir\", \"Acyclovir Lauriad\", \"ACYCLOVIR SODIUM\", \"Avirax\", \"Cargosil\", \"Cyclovir\", \"Genvir\", \"Gerpevir\", \"Hascovir\", \"Herpevir\", \"Maynar\", \"Poviral\", \"Sitavig\", \"Sitavir\", \"Vipral\", \"Virolex\", \"Viropump\", \"Virorax\", \"Zovirax\", \"Zovirax topical\", \"Zyclir\")" 4 "g" 4 "g"
"J05AF08" 60871 "Adefovir dipivoxil" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Adefovir di ester\", \"Adefovir dipivoxil\", \"Adefovir Dipivoxil\", \"Adefovir dipivoxyl\", \"Adefovir pivoxil\", \"Adefovirdipivoxl\", \"Bisadenine\", \"BISADENINE\", \"BisPMEA\", \"Hepsera\", \"Preveon\", \"YouHeDing\")" 10 "mg"
"J05AE05" 65016 "Amprenavir" "Protease inhibitors" "c(\"Agenerase\", \"Amprenavir\", \"Amprenavirum\", \"Prozei\", \"Vertex\")" 1.2 "g"
"J05AP06" 16076883 "Asunaprevir" "Antivirals for treatment of HCV infections" "c(\"Asunaprevir\", \"Sunvepra\")"
"J05AE08" 148192 "Atazanavir" "Protease inhibitors" "c(\"Atazanavir\", \"Atazanavir Base\", \"Latazanavir\", \"Reyataz\", \"Zrivada\")" 0.3 "g"
"J05AR15" 86583336 "Atazanavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR23" "Atazanavir and ritonavir" "Antivirals for treatment of HIV infections, combinations" "" 0.3 "g"
"J05AP03" 10324367 "Boceprevir" "Antivirals for treatment of HCV infections" "c(\"Bocepravir\", \"Boceprevir\", \"Victrelis\")" 2.4 "g"
"J05AB15" 446727 "Brivudine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Bridic\", \"Brivox\", \"Brivudin\", \"Brivudina\", \"Brivudine\", \"Brivudinum\", \"BrVdUrd\", \"Helpin\", \"Zerpex\", \"Zostex\")" 0.125 "g"
"J05AB12" 60613 "Cidofovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Cidofovir\", \"Cidofovir anhydrous\", \"Cidofovir gel\", \"Cidofovirum\", \"Forvade\", \"Vistide\")" 25 "mg"
"J05AF12" 73115 "Clevudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Clevudine\", \"Levovir\", \"Revovir\")" 30 "mg"
"J05AP07" 25154714 "Daclatasvir" "Antivirals for treatment of HCV infections" "c(\"Daclatasvir\", \"Daklinza\")" 60 "mg"
"J05AE10" 213039 "Darunavir" "Protease inhibitors" "c(\"Darunavir\", \"Darunavirum\", \"Prezista\", \"Prezista Naive\")" 1.2 "g"
"J05AR14" "Darunavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AP09" 56640146 "Dasabuvir" "Antivirals for treatment of HCV infections" "Dasabuvir" 0.5 "g"
"J05AP52" "Dasabuvir, ombitasvir, paritaprevir and ritonavir" "Antivirals for treatment of HCV infections" ""
"J05AG02" 5625 "Delavirdine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"BHAP der\", \"Delavirdin\", \"Delavirdina\", \"Delavirdine\", \"Delavirdinum\", \"PIPERAZINE\", \"Rescriptor\")" 1.2 "g"
"J05AF02" 135398739 "Didanosine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Didanosina\", \"Didanosine\", \"Didanosinum\", \"Dideoxyinosine\", \"DIDEOXYINOSINE\", \"Hypoxanthine ddN\", \"Videx\", \"Videx EC\")" 0.4 "g"
"J05AX12" 54726191 "Dolutegravir" "Other antivirals" "c(\"Dolutegravir\", \"Dolutegravir Sodium\", \"Soltegravir\", \"Tivicay\")" 50 "mg"
"J05AR21" 131801472 "Dolutegravir and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AG06" 58460047 "Doravirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Doravirine\", \"Pifeltro\")"
"J05AG03" 64139 "Efavirenz" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Efavirenz\", \"Efavirenzum\", \"Eravirenz\", \"Stocrin\", \"Strocin\", \"Sustiva\")" 0.6 "g"
"J05AP54" 91669168 "Elbasvir and grazoprevir" "Antivirals for treatment of HCV infections" ""
"J05AX11" 5277135 "Elvitegravir" "Other antivirals" "c(\"Elvitegravir\", \"Vitekta\")"
"J05AF09" 60877 "Emtricitabine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Coviracil\", \"Emtricitabin\", \"Emtricitabina\", \"Emtricitabine\", \"Emtricitabinum\", \"Emtritabine\", \"Emtriva\", \"Racivir\")" 0.2 "g"
"J05AR17" 90469070 "Emtricitabine and tenofovir alafenamide" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR20" "Emtricitabine, tenofovir alafenamide and bictegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR19" "Emtricitabine, tenofovir alafenamide and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR22" "Emtricitabine, tenofovir alafenamide, darunavir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR18" "Emtricitabine, tenofovir alafenamide, elvitegravir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR06" "Emtricitabine, tenofovir disoproxil and efavirenz" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR08" "Emtricitabine, tenofovir disoproxil and rilpivirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR09" "Emtricitabine, tenofovir disoproxil, elvitegravir and cobicistat" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX07" 16130199 "Enfuvirtide" "Other antivirals" "c(\"Enfurvitide\", \"Enfuvirtide\", \"Fuzeon\", \"Pentafuside\")" 0.18 "g"
"J05AX17" 10089466 "Enisamium iodide" "Other antivirals" "Enisamium iodide" 1.5 "g"
"J05AF10" 135398508 "Entecavir" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Baraclude\", \"Entecavir\", \"Entecavir anhydrous\", \"Entecavirum\")" 0.5 "mg"
"J05AG04" 193962 "Etravirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"DAPY deriv\", \"Etravine\", \"Etravirine\", \"Intelence\")" 0.4 "g"
"J05AP04" 42601552 "Faldaprevir" "Antivirals for treatment of HCV infections" "Faldaprevir"
"J05AB09" 3324 "Famciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Famciclovir\", \"Famciclovirum\", \"Famvir\", \"Oravir\")" 0.75 "g"
"J05AE07" 131536 "Fosamprenavir" "Protease inhibitors" "c(\"Amprenavir phosphate\", \"Fosamprenavir\", \"Lexiva\", \"Telzir\")" 1.4 "g"
"J05AD01" 3415 "Foscarnet" "Phosphonic acid derivatives" "c(\"Forscarnet\", \"Forscarnet sodium\", \"Foscarmet\", \"Foscarnet\", \"Phosphonoformate\", \"Phosphonoformic acid\")" 6.5 "g"
"J05AD02" 546 "Fosfonet" "Phosphonic acid derivatives" "c(\"Fosfonet\", \"Fosfonet sodium\", \"Fosfonet Sodium\", \"Fosfonoacetate\", \"Fosfonoacetic acid\", \"Phosphonacetate\", \"Phosphonacetic acid\")"
"J05AB06" 135398740 "Ganciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Citovirax\", \"Cymevan\", \"Cymeven\", \"Cymevene\", \"Cytovene\", \"Cytovene IV\", \"Ganciclovir\", \"Ganciclovirum\", \"Gancyclovir\", \"Hydroxyacyclovir\", \"Virgan\", \"Vitrasert\", \"Zirgan\")" 3 "g" 0.5 "g"
"J05AP57" "Glecaprevir and pibrentasvir" "Antivirals for treatment of HCV infections" ""
"J05AX23" "Ibalizumab" "Other antivirals" ""
"J05AB02" 5905 "Idoxuridine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Antizona\", \"Dendrid\", \"Emanil\", \"Heratil\", \"Herpesil\", \"Herpid\", \"Herpidu\", \"Herplex\", \"HERPLEX\", \"Herplex liquifilm\", \"Idexur\", \"Idossuridina\", \"Idoxene\", \"Idoxuridin\", \"Idoxuridina\", \"Idoxuridine\", \"Idoxuridinum\", \"Idu Oculos\", \"Iducher\", \"Idulea\", \"Iduoculos\", \"Iduridin\", \"Iduviran\", \"Iododeoxyridine\", \"Iododeoxyuridine\", \"Iodoxuridine\", \"Joddeoxiuridin\", \"Kerecid\", \"Kerecide\", \"Ophthalmadine\", \"Spectanefran\", \"Stoxil\", \"Synmiol\", \"Virudox\")"
"J05AE02" 5362440 "Indinavir" "Protease inhibitors" "c(\"Compound J\", \"Crixivan\", \"Indinavir\", \"Indinavir anhydrous\", \"Propolis+Indinavir\")" 2.4 "g"
"J05AX05" 135449284 "Inosine pranobex" "Other antivirals" "c(\"Aviral\", \"Delimmun\", \"Immunovir\", \"Imunovir\", \"Inosine pranobex\", \"Inosiplex\", \"Isoprinosin\", \"Isoprinosina\", \"Isoprinosine\", \"Isoviral\", \"Methisoprinol\", \"Methysoprinol\", \"Metisoprinol\", \"Viruxan\")" 3 "g"
"J05AF05" 60825 "Lamivudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Epivir\", \"Hepitec\", \"Heptivir\", \"Heptodin\", \"Heptovir\", \"Lamivir\", \"Lamivudin\", \"Lamivudina\", \"Lamivudine\", \"Lamivudinum\", \"Zeffix\")" 0.3 "g"
"J05AR02" "Lamivudine and abacavir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR16" 73386700 "Lamivudine and raltegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR12" "Lamivudine and tenofovir disoproxil" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR13" "Lamivudine, abacavir and dolutegravir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR24" "Lamivudine, tenofovir disoproxil and doravirine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR11" "Lamivudine, tenofovir disoproxil and efavirenz" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX18" 45138674 "Letermovir" "Other antivirals" "c(\"Letermovir\", \"Prevymis\")" 0.48 "g" 0.48 "g"
"J05AR10" 11979606 "Lopinavir and ritonavir" "Antivirals for treatment of HIV infections, combinations" "c(\"Aluvia\", \"Kaletra\")" 0.8 "g"
"J05AX02" 24839946 "Lysozyme" "Other antivirals" "c(\"Lysozyme chloride\", \"Lysozyme Chloride\", \"Lysozyme G\")"
"J05AX09" 3002977 "Maraviroc" "Other antivirals" "c(\"Celsentri\", \"Maraviroc\", \"Selzentry\")" 0.6 "g"
"J05AX10" 471161 "Maribavir" "Other antivirals" "c(\"Benzimidavir\", \"Camvia\", \"Maribavir\")"
"J05AA01" 667492 "Metisazone" "Thiosemicarbazones" "c(\"Kemoviran\", \"Marboran\", \"Marborane\", \"Methisazon\", \"Methisazone\", \"Methsazone\", \"Metisazon\", \"Metisazona\", \"Metisazone\", \"Metisazonum\", \"Viruzona\")"
"J05AX01" 71655 "Moroxydine" "Other antivirals" "c(\"Bimolin\", \"Flumidine\", \"Influmine\", \"Moroxidina\", \"Moroxydine\", \"Moroxydinum\", \"Vironil\", \"Virugon\", \"Virumin\", \"Wirumin\")" 0.3 "g"
"J05AE04" 64143 "Nelfinavir" "Protease inhibitors" "c(\"Nelfinavir\", \"Viracept\")" 2.25 "g"
"J05AG01" 4463 "Nevirapine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Nevirapine\", \"Nevirapine anhydrous\", \"Viramune\", \"Viramune IR\", \"Viramune XR\")" 0.4 "g"
"J05AP53" "Ombitasvir, paritaprevir and ritonavir" "Antivirals for treatment of HCV infections" ""
"J05AH02" 65028 "Oseltamivir" "Neuraminidase inhibitors" "c(\"Agucort\", \"Oseltamivir\", \"Tamiflu\", \"Tamvir\")" 0.15 "g"
"J05AB13" 135398748 "Penciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Adenovir\", \"Denavir\", \"Penciceovir\", \"Penciclovir\", \"Penciclovirum\", \"Pencyclovir\", \"Vectavir\")"
"J05AX21" 9942657 "Pentanedioic acid imidazolyl ethanamide" "Other antivirals" "Ingamine" 90 "mg"
"J05AH03" 154234 "Peramivir" "Neuraminidase inhibitors" "c(\"PeramiFlu\", \"Peramivir\", \"Rapiacta\", \"RAPIVAB\")"
"J05AX06" 1684 "Pleconaril" "Other antivirals" "c(\"Picovir\", \"Pleconaril\", \"Pleconarilis\")"
"J05AX08" 54671008 "Raltegravir" "Other antivirals" "c(\"Isentress\", \"Raltegravir\")" 0.8 "g"
"J05AP01" 37542 "Ribavirin" "Antivirals for treatment of HCV infections" "c(\"Copegus\", \"Cotronak\", \"Drug: Ribavirin\", \"Ravanex\", \"Rebetol\", \"Rebetron\", \"Rebretron\", \"Ribacine\", \"Ribamide\", \"Ribamidil\", \"Ribamidyl\", \"Ribasphere\", \"Ribavirin\", \"Ribavirin Capsules\", \"Ribavirina\", \"Ribavirine\", \"Ribavirinum\", \"Ribovirin\", \"Tribavirin\", \"Varazid\", \"Vilona\", \"Viramid\", \"Viramide\", \"Virazid\", \"Virazide\", \"Virazole\")" 1 "g"
"J05AG05" 6451164 "Rilpivirine" "Non-nucleoside reverse transcriptase inhibitors" "c(\"Edurant\", \"Rilpivirine\")" 25 "mg"
"J05AC02" 5071 "Rimantadine" "Cyclic amines" "c(\"Remantadine\", \"Riamantadine\", \"Rimant\", \"RIMANTADIN\", \"Rimantadin A\", \"Rimantadina\", \"Rimantadine\", \"Rimantadinum\")" 0.2 "g"
"J05AE03" 392622 "Ritonavir" "Protease inhibitors" "c(\"Norvir\", \"Norvir Sec\", \"Norvir Softgel\", \"Ritonavir\", \"Ritonavire\", \"Ritonavirum\")" 1.2 "g"
"J05AE01" 441243 "Saquinavir" "Protease inhibitors" "c(\"Fortovase\", \"Invirase\", \"Saquinavir\")" 1.8 "g"
"J05AP05" 24873435 "Simeprevir" "Antivirals for treatment of HCV infections" "c(\"Olysio\", \"Simeprevir sodium\")" 0.15 "g"
"J05AP08" 45375808 "Sofosbuvir" "Antivirals for treatment of HCV infections" "c(\"Hepcinat\", \"Hepcvir\", \"Sofosbuvir\", \"Sovaldi\", \"SOVALDI\", \"SoviHep\")" 0.4 "g"
"J05AP51" 72734365 "Sofosbuvir and ledipasvir" "Antivirals for treatment of HCV infections" ""
"J05AP55" 91885554 "Sofosbuvir and velpatasvir" "Antivirals for treatment of HCV infections" "Epclusa Tablet"
"J05AP56" "Sofosbuvir, velpatasvir and voxilaprevir" "Antivirals for treatment of HCV infections" ""
"J05AF04" 18283 "Stavudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Estavudina\", \"Sanilvudine\", \"Stavudin\", \"Stavudine\", \"Stavudinum\", \"Zerit Xr\", \"Zerut XR\")" 80 "mg"
"J05AR07" 15979285 "Stavudine, lamivudine and nevirapine" "Antivirals for treatment of HIV infections, combinations" "STAVUDIINE"
"J05AP02" 3010818 "Telaprevir" "Antivirals for treatment of HCV infections" "c(\"Incivek\", \"Incivo\", \"Telaprevir\", \"Telavic\")" 2.25 "g"
"J05AF11" 159269 "Telbivudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Epavudine\", \"Sebivo\", \"Telbivudin\", \"Telbivudine\", \"Tyzeka\")" 0.6 "g"
"J05AF13" 9574768 "Tenofovir alafenamide" "Nucleoside and nucleotide reverse transcriptase inhibitors" "Vemlidy" 25 "mg"
"J05AF07" 5481350 "Tenofovir disoproxil" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"BisPMPA\", \"PMPA prodrug\", \"Tenofovir\", \"Viread\")" 0.245 "g"
"J05AR03" "Tenofovir disoproxil and emtricitabine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AX19" 5475 "Tilorone" "Other antivirals" "c(\"Amiksin\", \"Amixin\", \"Amixin IC\", \"Amyxin\", \"Tiloron\", \"Tilorona\", \"Tilorone\", \"Tiloronum\")" 0.125 "g"
"J05AE09" 54682461 "Tipranavir" "Protease inhibitors" "c(\"Aptivus\", \"Tipranavir\")" 1 "g"
"J05AC03" 64377 "Tromantadine" "Cyclic amines" "c(\"Tromantadina\", \"Tromantadine\", \"Tromantadinum\", \"Viruserol\")"
"J05AX13" 131411 "Umifenovir" "Other antivirals" "c(\"Arbidol\", \"Arbidol base\", \"Umifenovir\")" 0.8 "g"
"J05AB11" 135398742 "Valaciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Talavir\", \"Valaciclovir\", \"Valaciclovirum\", \"ValACV\", \"Valcivir\", \"Valcyclovir\", \"Valtrex\", \"Virval\", \"Zelitrex\")" 3 "g"
"J05AB14" 135413535 "Valganciclovir" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Cymeval\", \"Valganciclovir\")" 0.9 "g"
"J05AB03" 21704 "Vidarabine" "Nucleosides and nucleotides excl. reverse transcriptase inhibitors" "c(\"Adenine arabinoside\", \"Araadenosine\", \"Arabinoside adenine\", \"Arabinosyl adenine\", \"Arabinosyladenine\", \"Spongoadenosine\", \"Vidarabin\", \"Vidarabina\", \"Vidarabine\", \"Vidarabine anhydrous\", \"Vidarabinum\", \"Vira A\", \"Vira ATM\")"
"J05AF03" 24066 "Zalcitabine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Dideoxycytidine\", \"Interferon AD + ddC\", \"Zalcitabine\", \"Zalcitibine\")" 2.25 "mg"
"J05AH01" 60855 "Zanamivir" "Neuraminidase inhibitors" "c(\"MODIFIED SIALIC ACID\", \"Relenza\", \"Zanamavir\", \"Zanamir\", \"Zanamivi\", \"Zanamivir\", \"Zanamivir hydrate\")"
"J05AF01" 35370 "Zidovudine" "Nucleoside and nucleotide reverse transcriptase inhibitors" "c(\"Azidothymidine\", \"AZT Antiviral\", \"Beta interferon\", \"Compound S\", \"Propolis+AZT\", \"Retrovir\", \"Zidovudina\", \"Zidovudine\", \"ZIDOVUDINE\", \"Zidovudine EP III\", \"Zidovudinum\")" 0.6 "g" 0.6 "g"
"J05AR01" "Zidovudine and lamivudine" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR04" "Zidovudine, lamivudine and abacavir" "Antivirals for treatment of HIV infections, combinations" ""
"J05AR05" "Zidovudine, lamivudine and nevirapine" "Antivirals for treatment of HIV infections, combinations" ""

BIN
data-raw/antivirals.xlsx Normal file

Binary file not shown.

1
data-raw/av.md5 Normal file
View File

@@ -0,0 +1 @@
7b6649442069d3d121f61ca3ff01843a

View File

@@ -1,205 +0,0 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# #
# 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 more info: https://msberends.github.io/AMR. #
# ==================================================================== #
# Read and format data ----------------------------------------------------
library(tidyverse)
library(maps)
library(httr)
GET_df <- function(ip) {
ip <- paste0("https://ipinfo.io/", ip, "?token=", ipinfo_token)
result <- ip %>% GET()
stop_for_status(result)
result %>%
content(type = "text", encoding = "UTF-8") %>%
jsonlite::fromJSON(flatten = TRUE) %>%
as_tibble()
}
# get website analytics
source("data-raw/country_analysis_url_token.R")
url_json <- paste0(country_analysis_url,
"/index.php?&module=API&token_auth=",
country_analysis_token,
"&method=Live.getLastVisitsDetails&idSite=3&language=en&expanded=1&date=2018-01-01,2028-01-01&period=range&filter_limit=-1&format=JSON&segment=&translateColumnNames=1")
data_json <- jsonlite::read_json(url_json)
data <- tibble(
timestamp_server = as.POSIXct(sapply(data_json, function(x) x$serverTimestamp), origin = "1970-01-01"),
ipaddress = sapply(data_json, function(x) x$visitIp))
rm(data_json)
# add country data based on IP address and ipinfo.io API
unique_ip <- unique(data$ipaddress)
ip_tbl <- GET_df(unique_ip[1])
p <- AMR:::progress_estimated(n = length(unique_ip) - 1, min_time = 0)
for (i in 2:length(unique_ip)) {
p$tick()
ip_tbl <- ip_tbl %>%
bind_rows(GET_df(unique_ip[i]))
}
close(p)
ip_tbl.bak <- ip_tbl
# add long and lat
ip_tbl <- ip_tbl %>%
separate(loc, into = c("y", "x"), sep = ",", remove = FALSE, convert = TRUE)
# Plot world map ----------------------------------------------------------
countries_geometry <- sf::st_as_sf(map('world', plot = FALSE, fill = TRUE)) %>%
mutate(countries_code = countrycode::countrycode(ID,
origin = 'country.name',
destination = 'iso2c',
custom_match = c("Ascension Island" = "GB", # Great Britain
"Azores" = "PT", # Portugal
"Barbuda" = "GB", # Great Britain
"Bonaire" = "BQ", # Bonaire, Saint Eustatius and Saba
"Canary Islands" = "ES", # Spain
"Chagos Archipelago" = "MU", # Mauritius
"Grenadines" = "VC", # Saint Vincent and the Grenadines
"Heard Island" = "AU", # Australia
"Kosovo" = "XK",
"Madeira Islands" = "PT", # Portugal
"Micronesia" = "FM",
"Saba" = "BQ", # Bonaire, Saint Eustatius and Saba
"Saint Martin" = "MF",
"Siachen Glacier" = "IN", # India
"Sint Eustatius" = "BQ" # Bonaire, Saint Eustatius and Saba
)),
included = as.integer(countries_code %in% ip_tbl$country),
not_antarctica = as.integer(ID != "Antarctica"),
countries_name = ifelse(included == 1, as.character(ID), NA))
# add countries not in the list
countries_missing <- unique(ip_tbl$country[!ip_tbl$country %in% countries_geometry$countries_code])
for (i in seq_len(length(countries_missing))) {
countries_geometry <- countries_geometry %>%
rbind(countries_geometry %>%
filter(ID == "Netherlands") %>%
mutate(ID = countrycode::countrycode(countries_missing[i],
origin = 'iso2c',
destination = 'country.name'),
countries_code = countries_missing[i],
included = 1,
not_antarctica = 1,
countries_name = countrycode::countrycode(countries_missing[i],
origin = 'iso2c',
destination = 'country.name')))
}
# how many?
countries_geometry %>% filter(included == 1) %>% nrow()
countries_geometry$countries_name <- gsub("UK", "United Kingdom", countries_geometry$countries_name, fixed = TRUE)
countries_geometry$countries_name <- gsub("USA", "United States", countries_geometry$countries_name, fixed = TRUE)
countries_plot <- ggplot(countries_geometry) +
geom_sf(aes(fill = included, colour = not_antarctica),
size = 0.25,
show.legend = FALSE) +
theme_minimal() +
theme(panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank()) +
scale_fill_gradient(low = "white", high = "#128f7645") +
# this makes the border Antarctica turn white (invisible):
scale_colour_gradient(low = "white", high = "#128f76")
countries_plot_mini <- countries_plot
countries_plot_mini$data <- countries_plot_mini$data %>% filter(ID != "Antarctica")
# countries_plot_mini <- countries_plot_mini + scale_colour_gradient(low = "#81899B", high = "#81899B")
countries_plot_big <- countries_plot +
labs(title = tools::toTitleCase("Countries the AMR package for R was downloaded from"),
subtitle = paste0("Between March 2018 (first release) and ",
format(Sys.Date(), "%B %Y")),
caption = "Source: https://cran-logs.rstudio.com") +
theme(plot.title = element_text(size = 16, hjust = 0.5),
plot.subtitle = element_text(size = 12, hjust = 0.5)) +
geom_text(aes(x = -170,
y = -75,
label = stringr::str_wrap(paste0("Countries (n = ",
length(countries_name[!is.na(countries_name)]), "): ",
paste(sort(countries_name[!is.na(countries_name)]), collapse = ", ")),
200)),
hjust = 0,
size = 4)
# main website page
ggsave("pkgdown/logos/countries.png",
width = 6,
height = 2.5,
units = "in",
dpi = 100,
plot = countries_plot_mini,
scale = 1)
# when clicked - a high res enlargement
ggsave("pkgdown/logos/countries_large.png",
width = 11,
height = 6,
units = "in",
dpi = 300,
plot = countries_plot_big,
scale = 1.5)
# Gibberish ---------------------------------------------------------------
data %>%
left_join(ip_tbl, by = c("ipaddress" = "ip")) %>%
group_by(country = countrycode::countrycode(country,
origin = 'iso2c',
destination = 'country.name')) %>%
summarise(first = min(timestamp_server)) %>%
arrange(desc(first)) %>%
mutate(frame = case_when(first <= as.POSIXct("2019-06-30") ~ "Q1-Q2 2019",
first <= as.POSIXct("2019-12-31") ~ "Q3-Q4 2019",
TRUE ~ "Q1-Q2 2020")) %>%
View()
#
# p1 <- data %>%
# group_by(country) %>%
# summarise(first = min(timestamp_server)) %>%
# arrange(first) %>%
# mutate(n = row_number()) %>%
# ggplot(aes(x = first, y = n)) +
# geom_line() +
# geom_point(aes(x = max(first), y = max(n)), size = 3) +
# scale_x_datetime(date_breaks = "2 months", date_labels = "%B %Y") +
# labs(x = NULL, y = "Number of countries")
#
# package_releases <- read_html("https://cran.r-project.org/src/contrib/Archive/AMR/") %>%
# rvest::html_table() %>%
# .[[1]] %>%
# as_tibble(.name_repair = "unique") %>%
# filter(`Last modified` != "") %>%
# transmute(version = gsub("[^0-9.]", "",
# gsub(".tar.gz", "", Name)),
# datetime = as.POSIXct(`Last modified`)) %>%
# # add current
# bind_rows(tibble(version = as.character(packageVersion("AMR")),
# datetime = as.POSIXct(packageDate("AMR")))) %>%
# # remove the ones not plottable
# filter(datetime > min(p1$data$first))
#
# p1 + geom_linerange(data = package_releases, aes(x = datetime, ymin = 0, ymax = 80), colour = "red", inherit.aes = FALSE)
#

BIN
data-raw/dosage.dta Normal file

Binary file not shown.

1
data-raw/dosage.md5 Normal file
View File

@@ -0,0 +1 @@
42d032c419117561e5c4b5b402e16f01

BIN
data-raw/dosage.rds Normal file

Binary file not shown.

BIN
data-raw/dosage.sas Normal file

Binary file not shown.

BIN
data-raw/dosage.sav Normal file

Binary file not shown.

136
data-raw/dosage.txt Normal file
View File

@@ -0,0 +1,136 @@
"ab" "name" "type" "dose" "dose_times" "administration" "notes" "original_txt" "eucast_version"
"AMK" "Amikacin" "standard_dosage" "25-30 mg/kg" 1 "iv" "" "25-30 mg/kg x 1 iv" 11
"AMX" "Amoxicillin" "high_dosage" "2 g" 6 "iv" "" "2 g x 6 iv" 11
"AMX" "Amoxicillin" "standard_dosage" "1 g" 3 "iv" "" "1 g x 3-4 iv" 11
"AMX" "Amoxicillin" "high_dosage" "0.75-1 g" 3 "oral" "" "0.75-1 g x 3 oral" 11
"AMX" "Amoxicillin" "standard_dosage" "0.5 g" 3 "oral" "" "0.5 g x 3 oral" 11
"AMX" "Amoxicillin" "uncomplicated_uti" "0.5 g" 3 "oral" "" "0.5 g x 3 oral" 11
"AMC" "Amoxicillin/clavulanic acid" "high_dosage" "2 g + 0.2 g" 3 "iv" "" "(2 g amoxicillin + 0.2 g clavulanic acid) x 3 iv" 11
"AMC" "Amoxicillin/clavulanic acid" "standard_dosage" "1 g + 0.2 g" 3 "iv" "" "(1 g amoxicillin + 0.2 g clavulanic acid) x 3-4 iv" 11
"AMC" "Amoxicillin/clavulanic acid" "high_dosage" "0.875 g + 0.125 g" 3 "oral" "" "(0.875 g amoxicillin + 0.125 g clavulanic acid) x 3 oral" 11
"AMC" "Amoxicillin/clavulanic acid" "standard_dosage" "0.5 g + 0.125 g" 3 "oral" "" "(0.5 g amoxicillin + 0.125 g clavulanic acid) x 3 oral" 11
"AMC" "Amoxicillin/clavulanic acid" "uncomplicated_uti" "0.5 g + 0.125 g" 3 "oral" "" "(0.5 g amoxicillin + 0.125 g clavulanic acid) x 3 oral" 11
"AMP" "Ampicillin" "high_dosage" "2 g" 4 "iv" "" "2 g x 4 iv" 11
"AMP" "Ampicillin" "standard_dosage" "2 g" 3 "iv" "" "2 g x 3 iv" 11
"SAM" "Ampicillin/sulbactam" "high_dosage" "2 g + 1 g" 4 "iv" "" "(2 g ampicillin + 1 g sulbactam) x 4 iv" 11
"SAM" "Ampicillin/sulbactam" "standard_dosage" "2 g + 1 g" 3 "iv" "" "(2 g ampicillin + 1 g sulbactam) x 3 iv" 11
"AZM" "Azithromycin" "standard_dosage" "0.5 g" 1 "oral" "or 0.5 g x 1 iv" "0.5 g x 1 oral or 0.5 g x 1 iv" 11
"ATM" "Aztreonam" "high_dosage" "2 g" 4 "iv" "" "2 g x 4 iv" 11
"ATM" "Aztreonam" "standard_dosage" "1 g" 3 "iv" "" "1 g x 3 iv" 11
"PEN" "Benzylpenicillin" "high_dosage" "1.2 g" 4 "iv" "" "1.2 g (2 MU) x 4-6 iv" 11
"PEN" "Benzylpenicillin" "standard_dosage" "0.6 g" 4 "iv" "" "0.6 g (1 MU) x 4 iv" 11
"CEC" "Cefaclor" "high_dosage" "1 g" 3 "oral" "" "1 g x 3 oral" 11
"CEC" "Cefaclor" "standard_dosage" "0.25-0.5 g" 3 "oral" "depending on species and/or infection type" "0.25-0.5 g x 3 oral depending on species and/or infection type" 11
"CFR" "Cefadroxil" "standard_dosage" "0.5-1 g" 2 "oral" "" "0.5-1 g x 2 oral" 11
"CFR" "Cefadroxil" "uncomplicated_uti" "0.5-1 g" 2 "oral" "" "0.5-1 g x 2 oral" 11
"CZO" "Cefazolin" "high_dosage" "2 g" 3 "iv" "" "2 g x 3 iv" 11
"CZO" "Cefazolin" "standard_dosage" "1 g" 3 "iv" "" "1 g x 3 iv" 11
"FEP" "Cefepime" "high_dosage" "2 g" 3 "iv" "" "2 g x 3 iv" 11
"FEP" "Cefepime" "standard_dosage" "1 g" 3 "iv" "or 2 g x 2 iv" "1 g x 3 iv or 2 g x 2 iv" 11
"FDC" "Cefiderocol" "standard_dosage" "2 g" 3 "iv" "over 3 hours" "2 g x 3 iv over 3 hours" 11
"CFM" "Cefixime" "standard_dosage" "0.2-0.4 g" 2 "oral" "" "0.2-0.4 g x 2 oral" 11
"CFM" "Cefixime" "uncomplicated_uti" "0.2-0.4 g" 2 "oral" "" "0.2-0.4 g x 2 oral" 11
"CTX" "Cefotaxime" "high_dosage" "2 g" 3 "iv" "" "2 g x 3 iv" 11
"CTX" "Cefotaxime" "standard_dosage" "1 g" 3 "iv" "" "1 g x 3 iv" 11
"CPD" "Cefpodoxime" "standard_dosage" "0.1-0.2 g" 2 "oral" "" "0.1-0.2 g x 2 oral" 11
"CPD" "Cefpodoxime" "uncomplicated_uti" "0.1-0.2 g" 2 "oral" "" "0.1-0.2 g x 2 oral" 11
"CPT" "Ceftaroline" "high_dosage" "0.6 g" 3 "iv" "over 2 hours" "0.6 g x 3 iv over 2 hours" 11
"CPT" "Ceftaroline" "standard_dosage" "0.6 g" 2 "iv" "over 1 hour" "0.6 g x 2 iv over 1 hour" 11
"CAZ" "Ceftazidime" "high_dosage" "2 g" 3 "iv" "or 1 g x 6 iv" "2 g x 3 iv or 1 g x 6 iv" 11
"CAZ" "Ceftazidime" "standard_dosage" "1 g" 3 "iv" "" "1 g x 3 iv" 11
"CZA" "Ceftazidime/avibactam" "standard_dosage" "2 g + 0.5 g" 3 "iv" "over 2 hours" "(2 g ceftazidime + 0.5 g avibactam) x 3 iv over 2 hours" 11
"CTB" "Ceftibuten" "standard_dosage" "0.4 g" 1 "oral" "" "0.4 g x 1 oral" 11
"BPR" "Ceftobiprole" "standard_dosage" "0.5 g" 3 "iv" "over 2 hours" "0.5 g x 3 iv over 2 hours" 11
"CZT" "Ceftolozane/tazobactam" "standard_dosage" "1 g + 0.5 g" 3 "iv" "over 1 hour" "(1 g ceftolozane + 0.5 g tazobactam) x 3 iv over 1 hour" 11
"CZT" "Ceftolozane/tazobactam" "standard_dosage" "2 g + 1 g" 3 "iv" "over 1 hour" "(2 g ceftolozane + 1 g tazobactam) x 3 iv over 1 hour" 11
"CRO" "Ceftriaxone" "high_dosage" "2 g" 2 "iv" "or 4 g x 1 iv" "2 g x 2 iv or 4 g x 1 iv" 11
"CRO" "Ceftriaxone" "standard_dosage" "2 g" 1 "iv" "" "2 g x 1 iv" 11
"CXM" "Cefuroxime" "high_dosage" "1.5 g" 3 "iv" "" "1.5 g x 3 iv" 11
"CXM" "Cefuroxime" "standard_dosage" "0.75 g" 3 "iv" "" "0.75 g x 3 iv" 11
"CXM" "Cefuroxime" "high_dosage" "0.5 g" 2 "oral" "" "0.5 g x 2 oral" 11
"CXM" "Cefuroxime" "standard_dosage" "0.25 g" 2 "oral" "" "0.25 g x 2 oral" 11
"CXM" "Cefuroxime" "uncomplicated_uti" "0.25 g" 2 "oral" "" "0.25 g x 2 oral" 11
"LEX" "Cephalexin" "standard_dosage" "0.25-1 g" 2 "oral" "" "0.25-1 g x 2-3 oral" 11
"LEX" "Cephalexin" "uncomplicated_uti" "0.25-1 g" 2 "oral" "" "0.25-1 g x 2-3 oral" 11
"CHL" "Chloramphenicol" "high_dosage" "2 g" 4 "oral" "or 2 g x 4 iv" "2 g x 4 oral or 2 g x 4 iv" 11
"CHL" "Chloramphenicol" "standard_dosage" "1 g" 4 "oral" "or 1 g x 4 iv" "1 g x 4 oral or 1 g x 4 iv" 11
"CIP" "Ciprofloxacin" "high_dosage" "0.75 g" 2 "oral" "or 0.4 g x 3 iv" "0.75 g x 2 oral or 0.4 g x 3 iv" 11
"CIP" "Ciprofloxacin" "standard_dosage" "0.5 g" 2 "oral" "or 0.4 g x 2 iv" "0.5 g x 2 oral or 0.4 g x 2 iv" 11
"CLR" "Clarithromycin" "high_dosage" "0.5 g" 2 "oral" "" "0.5 g x 2 oral" 11
"CLR" "Clarithromycin" "standard_dosage" "0.25 g" 2 "oral" "" "0.25 g x 2 oral" 11
"CLI" "Clindamycin" "high_dosage" "0.3 g" 4 "oral" "or 0.9 g x 3 iv" "0.3 g x 4 oral or 0.9 g x 3 iv" 11
"CLI" "Clindamycin" "standard_dosage" "0.3 g" 2 "oral" "or 0.6 g x 3 iv" "0.3 g x 2 oral or 0.6 g x 3 iv" 11
"CLO" "Cloxacillin" "high_dosage" "1 g" 4 "oral" "or 2 g x 6 iv" "1 g x 4 oral or 2 g x 6 iv" 11
"CLO" "Cloxacillin" "standard_dosage" "0.5 g" 4 "oral" "or 1 g x 4 iv" "0.5 g x 4 oral or 1 g x 4 iv" 11
"COL" "Colistin" "standard_dosage" "4.5 MU" 2 "iv" "loading dose of 9 MU" "4.5 MU x 2 iv with a loading dose of 9 MU" 11
"DAL" "Dalbavancin" "standard_dosage" "1 g" 1 "iv" "over 30 minutes on day 8" "1 g x 1 iv over 30 minutes on day 1 If needed, 0.5 g x 1 iv over 30 minutes on day 8" 11
"DAP" "Daptomycin" "standard_dosage" "4 mg/kg" 1 "iv" "" "4 mg/kg x 1 iv" 11
"DAP" "Daptomycin" "standard_dosage" "6 mg/kg" 1 "iv" "" "6 mg/kg x 1 iv" 11
"DFX" "Delafloxacin" "standard_dosage" "0.45 g" 2 "oral" "or 0.3 g x 2 iv" "0.45 g x 2 oral or 0.3 g x 2 iv" 11
"DIC" "Dicloxacillin" "high_dosage" "2 g" 4 "oral" "or 2 g x 6 iv" "2 g x 4 oral or 2 g x 6 iv" 11
"DIC" "Dicloxacillin" "standard_dosage" "0.5-1 g" 4 "oral" "or 1 g x 4 iv" "0.5-1 g x 4 oral or 1 g x 4 iv" 11
"DOR" "Doripenem" "high_dosage" "1 g" 3 "iv" "over 1 hour" "1 g x 3 iv over 1 hour" 11
"DOR" "Doripenem" "standard_dosage" "0.5 g" 3 "iv" "over 1 hour" "0.5 g x 3 iv over 1 hour" 11
"DOX" "Doxycycline" "high_dosage" "0.2 g" 1 "oral" "" "0.2 g x 1 oral" 11
"DOX" "Doxycycline" "standard_dosage" "0.1 g" 1 "oral" "" "0.1 g x 1 oral" 11
"ERV" "Eravacycline" "standard_dosage" "1 mg/kg" 2 "iv" "" "1 mg/kg x 2 iv" 11
"ETP" "Ertapenem" "standard_dosage" "1 g" 1 "iv" "over 30 minutes" "1 g x 1 iv over 30 minutes" 11
"ERY" "Erythromycin" "high_dosage" "1 g" 4 "oral" "or 1 g x 4 iv" "1 g x 4 oral or 1 g x 4 iv" 11
"ERY" "Erythromycin" "standard_dosage" "0.5 g" 2 "oral" "or 0.5 g x 2-4 iv" "0.5 g x 2-4 oral or 0.5 g x 2-4 iv" 11
"FDX" "Fidaxomicin" "standard_dosage" "0.2 g" 2 "oral" "" "0.2 g x 2 oral" 11
"FLC" "Flucloxacillin" "high_dosage" "1 g" 4 "oral" "or 2 g x 6 iv" "1 g x 4 oral or 2 g x 6 iv" 11
"FLC" "Flucloxacillin" "standard_dosage" "1 g" 3 "oral" "or 2 g x 4 iv (or 1 g x 6 iv)" "1 g x 3 oral or 2 g x 4 iv (or 1 g x 6 iv)" 11
"FOS" "Fosfomycin" "high_dosage" "8 g" 3 "iv" "" "8 g x 3 iv" 11
"FOS" "Fosfomycin" "standard_dosage" "4 g" 3 "iv" "" "4 g x 3 iv" 11
"FUS" "Fusidic acid" "high_dosage" "0.5 g" 3 "oral" "or 0.5 g x 3 iv" "0.5 g x 3 oral or 0.5 g x 3 iv" 11
"FUS" "Fusidic acid" "standard_dosage" "0.5 g" 2 "oral" "or 0.5 g x 2 iv" "0.5 g x 2 oral or 0.5 g x 2 iv" 11
"GEN" "Gentamicin" "standard_dosage" "6-7 mg/kg" 1 "iv" "" "6-7 mg/kg x 1 iv" 11
"IPM" "Imipenem" "high_dosage" "1 g" 4 "iv" "over 30 minutes" "1 g x 4 iv over 30 minutes" 11
"IPM" "Imipenem" "standard_dosage" "0.5 g" 4 "iv" "over 30 minutes" "0.5 g x 4 iv over 30 minutes" 11
"IMR" "Imipenem/relebactam" "standard_dosage" "0.5 g + 0.25 g" 4 "iv" "over 30 minutes" "(0.5 g imipenem + 0.25 g relebactam) x 4 iv over 30 minutes" 11
"LMU" "Lefamulin" "standard_dosage" "0.15 g" 2 "iv" "or 0.6 g x 2 oral" "0.15 g x 2 iv or 0.6 g x 2 oral" 11
"LVX" "Levofloxacin" "high_dosage" "0.5 g" 2 "oral" "or 0.5 g x 2 iv" "0.5 g x 2 oral or 0.5 g x 2 iv" 11
"LVX" "Levofloxacin" "standard_dosage" "0.5 g" 1 "oral" "or 0.5 g x 1 iv" "0.5 g x 1 oral or 0.5 g x 1 iv" 11
"LNZ" "Linezolid" "standard_dosage" "0.6 g" 2 "oral" "or 0.6 g x 2 iv" "0.6 g x 2 oral or 0.6 g x 2 iv" 11
"MEM" "Meropenem" "high_dosage" "2 g" 3 "iv" "over 3 hours" "2 g x 3 iv over 3 hours" 11
"MEM" "Meropenem" "standard_dosage" "1 g" 3 "iv" "over 30 minutes" "1 g x 3 iv over 30 minutes" 11
"MEV" "Meropenem/vaborbactam" "standard_dosage" "2 g + 2 g" 3 "iv" "over 3 hours" "(2 g meropenem + 2 g vaborbactam) x 3 iv over 3 hours" 11
"MTR" "Metronidazole" "high_dosage" "0.5 g" 3 "oral" "or 0.5 g x 3 iv" "0.5 g x 3 oral or 0.5 g x 3 iv" 11
"MTR" "Metronidazole" "standard_dosage" "0.4 g" 3 "oral" "or 0.4 g x 3 iv" "0.4 g x 3 oral or 0.4 g x 3 iv" 11
"MNO" "Minocycline" "standard_dosage" "0.1 g" 2 "oral" "" "0.1 g x 2 oral" 11
"MFX" "Moxifloxacin" "standard_dosage" "0.4 g" 1 "oral" "or 0.4 g x 1 iv" "0.4 g x 1 oral or 0.4 g x 1 iv" 11
"OFX" "Ofloxacin" "high_dosage" "0.4 g" 2 "oral" "or 0.4 g x 2 iv" "0.4 g x 2 oral or 0.4 g x 2 iv" 11
"OFX" "Ofloxacin" "standard_dosage" "0.2 g" 2 "oral" "or 0.2 g x 2 iv" "0.2 g x 2 oral or 0.2 g x 2 iv" 11
"ORI" "Oritavancin" "standard_dosage" "1.2 g" 1 "iv" "" "1.2 g x 1 (single dose) iv over 3 hours" 11
"OXA" "Oxacillin" "high_dosage" "1 g" 6 "iv" "" "1 g x 6 iv" 11
"OXA" "Oxacillin" "standard_dosage" "1 g" 4 "iv" "" "1 g x 4 iv" 11
"PHN" "Phenoxymethylpenicillin" "standard_dosage" "0.5-2 g" 3 "oral" "depending on species and/or infection type" "0.5-2 g x 3-4 oral depending on species and/or infection type" 11
"PIP" "Piperacillin" "high_dosage" "4 g" 4 "iv" "" "4 g x 4 iv by extended 3-hour infusion" 11
"PIP" "Piperacillin" "standard_dosage" "4 g" 4 "iv" "" "4 g x 4 iv" 11
"TZP" "Piperacillin/tazobactam" "high_dosage" "4 g + 0.5 g" 4 "iv" "" "(4 g piperacillin + 0.5 g tazobactam) x 4 iv by extended 3-hour infusion" 11
"TZP" "Piperacillin/tazobactam" "standard_dosage" "4 g + 0.5 g" 4 "iv" "" "(4 g piperacillin + 0.5 g tazobactam) x 4 iv or x 3 by extended 4-hour infusion" 11
"QDA" "Quinupristin/dalfopristin" "high_dosage" "7.5 mg/kg" 3 "iv" "" "7.5 mg/kg x 3 iv" 11
"QDA" "Quinupristin/dalfopristin" "standard_dosage" "7.5 mg/kg" 2 "iv" "" "7.5 mg/kg x 2 iv" 11
"RIF" "Rifampicin" "high_dosage" "0.6 g" 2 "oral" "or 0.6 g x 2 iv" "0.6 g x 2 oral or 0.6 g x 2 iv" 11
"RIF" "Rifampicin" "standard_dosage" "0.6 g" 1 "oral" "or 0.6 g x 1 iv" "0.6 g x 1 oral or 0.6 g x 1 iv" 11
"RXT" "Roxithromycin" "standard_dosage" "0.15 g" 2 "oral" "" "0.15 g x 2 oral" 11
"SPT" "Spectinomycin" "standard_dosage" "2 g" 1 "im" "" "2 g x 1 im" 11
"TZD" "Tedizolid" "standard_dosage" "0.2 g" 1 "oral" "or 0.2 g x 1 iv" "0.2 g x 1 oral or 0.2 g x 1 iv" 11
"TEC" "Teicoplanin" "high_dosage" "0.8 g" 1 "iv" "" "0.8 g x 1 iv" 11
"TEC" "Teicoplanin" "standard_dosage" "0.4 g" 1 "iv" "" "0.4 g x 1 iv" 11
"TLV" "Telavancin" "standard_dosage" "10 mg/kg" 1 "iv" "over 1 hour" "10 mg/kg x 1 iv over 1 hour" 11
"TLT" "Telithromycin" "standard_dosage" "0.8 g" 1 "oral" "" "0.8 g x 1 oral" 11
"TEM" "Temocillin" "high_dosage" "2 g" 3 "iv" "" "2 g x 3 iv" 11
"TEM" "Temocillin" "standard_dosage" "2 g" 2 "iv" "" "2 g x 2 iv" 11
"TCY" "Tetracycline" "high_dosage" "0.5 g" 4 "oral" "" "0.5 g x 4 oral" 11
"TCY" "Tetracycline" "standard_dosage" "0.25 g" 4 "oral" "" "0.25 g x 4 oral" 11
"TIC" "Ticarcillin" "high_dosage" "3 g" 6 "iv" "" "3 g x 6 iv" 11
"TIC" "Ticarcillin" "standard_dosage" "3 g" 4 "iv" "" "3 g x 4 iv" 11
"TCC" "Ticarcillin/clavulanic acid" "high_dosage" "3 g + 0.1 g" 6 "iv" "" "(3 g ticarcillin + 0.1 g clavulanic acid) x 6 iv" 11
"TCC" "Ticarcillin/clavulanic acid" "standard_dosage" "3 g + 0.1-0.2 g" 4 "iv" "" "(3 g ticarcillin + 0.1-0.2 g clavulanic acid) x 4 iv" 11
"TGC" "Tigecycline" "standard_dosage" "0.1 g" "loading dose followed by 50 mg x 2 iv" "0.1 g loading dose followed by 50 mg x 2 iv" 11
"TOB" "Tobramycin" "standard_dosage" "6-7 mg/kg" 1 "iv" "" "6-7 mg/kg x 1 iv" 11
"SXT" "Trimethoprim/sulfamethoxazole" "high_dosage" "0.24 g + 1.2 g" 2 "oral" "" "(0.24 g trimethoprim + 1.2 g sulfamethoxazole) x 2 oral or (0.24 g trimethoprim + 1.2 g sulfamethoxazole) x 2 iv" 11
"SXT" "Trimethoprim/sulfamethoxazole" "standard_dosage" "0.16 g + 0.8 g" 2 "oral" "" "(0.16 g trimethoprim + 0.8 g sulfamethoxazole) x 2 oral or (0.16 g trimethoprim + 0.8 g sulfamethoxazole) x 2 iv" 11
"SXT" "Trimethoprim/sulfamethoxazole" "uncomplicated_uti" "0.16 g + 0.8 g" 2 "oral" "" "(0.16 g trimethoprim + 0.8 g sulfamethoxazole) x 2 oral" 11
"VAN" "Vancomycin" "standard_dosage" "0.5 g" 4 "iv" "or 1 g x 2 iv or 2 g x 1 by continuous infusion" "0.5 g x 4 iv or 1 g x 2 iv or 2 g x 1 by continuous infusion" 11

BIN
data-raw/dosage.xlsx Normal file

Binary file not shown.

Binary file not shown.

BIN
data-raw/download_dta.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

BIN
data-raw/download_r.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
data-raw/download_sas.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

BIN
data-raw/download_sav.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

BIN
data-raw/download_txt.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
data-raw/download_xlsx.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -1,191 +1,414 @@
# -------------------------------------------------------------------------------------------------------------------------------
# For editing this EUCAST reference file, these values can all be used for target antibiotics:
# 'all_betalactams', 'aminoglycosides', 'aminopenicillins', 'carbapenems', 'cephalosporins', 'cephalosporins_except_CAZ',
# 'fluoroquinolones', 'glycopeptides', 'macrolides', 'polymyxins', 'streptogramins', 'tetracyclines', 'ureidopenicillins'
# For editing this EUCAST reference file, these values can all be used for targeting antibiotics:
# 'all_betalactams', 'aminoglycosides', 'aminopenicillins', 'carbapenems', 'cephalosporins', 'cephalosporins_1st', 'cephalosporins_2nd', 'cephalosporins_3rd', 'cephalosporins_except_CAZ',
# 'fluoroquinolones', 'glycopeptides', 'lincosamides', 'lipoglycopeptides', 'macrolides', 'oxazolidinones', 'polymyxins', 'streptogramins', 'tetracyclines', 'ureidopenicillins',
# and all separate EARS-Net letter codes like 'AMC'. They can be separated by comma: 'AMC, fluoroquinolones'.
# The 'if_mo_property' column can be any column name from the AMR::microorganisms data set, or "genus_species" or "gramstain".
# The like.is.one_of column must be 'like' or 'is' or 'one_of' ('like' will read the 'this_value' column as regular expression)
# The EUCAST guideline contains references to the 'Burkholderia cepacia complex'. All species in this group are noted on the 'B.cepacia' sheet of the EUCAST Clinical Breakpoint v.10.0 Excel file of 2020 (v_10.0_Breakpoint_Tables.xlsx).
# >>>>> IF YOU WANT TO IMPORT THIS FILE INTO YOUR OWN SOFTWARE, HAVE THE FIRST 10 LINES SKIPPED <<<<<
# -------------------------------------------------------------------------------------------------------------------------------
if_mo_property like.is.one_of this_value and_these_antibiotics have_these_values then_change_these_antibiotics to_value reference.rule reference.rule_group
order is Enterobacterales AMP S AMX S Enterobacterales (Order) Breakpoints
order is Enterobacterales AMP I AMX I Enterobacterales (Order) Breakpoints
order is Enterobacterales AMP R AMX R Enterobacterales (Order) Breakpoints
genus is Staphylococcus PEN, FOX S AMP, AMX, PIP, TIC S Staphylococcus Breakpoints
genus is Staphylococcus PEN, FOX R, S OXA, FLC S Staphylococcus Breakpoints
genus is Staphylococcus FOX R all_betalactams R Staphylococcus Breakpoints
genus_species is Staphylococcus saprophyticus AMP S AMX, AMC, PIP, TZP S Staphylococcus Breakpoints
genus is Staphylococcus FOX S carbapenems, cephalosporins_except_CAZ S Staphylococcus Breakpoints
genus is Staphylococcus FOX I carbapenems, cephalosporins_except_CAZ I Staphylococcus Breakpoints
genus is Staphylococcus FOX R carbapenems, cephalosporins_except_CAZ R Staphylococcus Breakpoints
genus is Staphylococcus NOR S CIP, LVX, MFX, OFX S Staphylococcus Breakpoints
genus is Staphylococcus ERY S AZM, CLR, RXT S Staphylococcus Breakpoints
genus is Staphylococcus ERY I AZM, CLR, RXT I Staphylococcus Breakpoints
genus is Staphylococcus ERY R AZM, CLR, RXT R Staphylococcus Breakpoints
genus is Staphylococcus TCY S DOX, MNO S Staphylococcus Breakpoints
genus is Enterococcus AMP S AMX, AMC, PIP, TZP S Enterococcus Breakpoints
genus is Enterococcus AMP I AMX, AMC, PIP, TZP I Enterococcus Breakpoints
genus is Enterococcus AMP R AMX, AMC, PIP, TZP R Enterococcus Breakpoints
genus is Enterococcus NOR S CIP, LVX S Enterococcus Breakpoints
genus is Enterococcus NOR I CIP, LVX I Enterococcus Breakpoints
genus is Enterococcus NOR R CIP, LVX R Enterococcus Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ PEN S aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC S Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ PEN I aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC I Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ PEN R aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC R Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ NOR S MFX S Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ NOR S LVX I Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ ERY S AZM, CLR, RXT S Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ ERY I AZM, CLR, RXT I Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ ERY R AZM, CLR, RXT R Streptococcus groups A, B, C, G Breakpoints
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G)$ TCY S DOX, MNO S Streptococcus groups A, B, C, G Breakpoints
genus_species is Streptococcus pneumoniae PEN S AMP, AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae AMP S AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae AMP I AMX, AMC, PIP, TZP I Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae AMP R AMX, AMC, PIP, TZP R Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae NOR S MFX S Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae NOR S LVX I Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae ERY S AZM, CLR, RXT S Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae ERY I AZM, CLR, RXT I Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae ERY R AZM, CLR, RXT R Streptococcus pneumoniae Breakpoints
genus_species is Streptococcus pneumoniae TCY S DOX, MNO S Streptococcus pneumoniae Breakpoints
genus_species like ^Streptococcus (australis|bovis|constellatus|cristatus|gallolyticus|gordonii|infantarius|infantis|mitis|mutans|oligofermentans|oralis|peroris|pseudopneumoniae|salivarius|sinensis|sobrinus|thermophilus|vestibularis|anginosus|equinus|intermedius|parasanguinis|sanguinis)$ PEN S AMP, AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints
genus_species like ^Streptococcus (australis|bovis|constellatus|cristatus|gallolyticus|gordonii|infantarius|infantis|mitis|mutans|oligofermentans|oralis|peroris|pseudopneumoniae|salivarius|sinensis|sobrinus|thermophilus|vestibularis|anginosus|equinus|intermedius|parasanguinis|sanguinis)$ AMP S AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints
genus_species like ^Streptococcus (australis|bovis|constellatus|cristatus|gallolyticus|gordonii|infantarius|infantis|mitis|mutans|oligofermentans|oralis|peroris|pseudopneumoniae|salivarius|sinensis|sobrinus|thermophilus|vestibularis|anginosus|equinus|intermedius|parasanguinis|sanguinis)$ AMP I AMX, AMC, PIP, TZP I Viridans group streptococci Breakpoints
genus_species like ^Streptococcus (australis|bovis|constellatus|cristatus|gallolyticus|gordonii|infantarius|infantis|mitis|mutans|oligofermentans|oralis|peroris|pseudopneumoniae|salivarius|sinensis|sobrinus|thermophilus|vestibularis|anginosus|equinus|intermedius|parasanguinis|sanguinis)$ AMP R AMX, AMC, PIP, TZP R Viridans group streptococci Breakpoints
genus_species is Haemophilus influenzae AMP S AMX, PIP S Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae AMP I AMX, PIP I Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae AMP R AMX, PIP R Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae PEN S AMP, AMX, AMC, PIP, TZP S Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae AMC S TZP S Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae AMC I TZP I Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae AMC R TZP R Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae NAL S CIP, LVX, MFX, OFX S Haemophilus influenzae Breakpoints
genus_species is Haemophilus influenzae TCY S DOX, MNO S Haemophilus influenzae Breakpoints
genus_species is Moraxella catarrhalis AMC S TZP S Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis AMC I TZP I Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis AMC R TZP R Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis NAL S CIP, LVX, MFX, OFX S Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis ERY S AZM, CLR, RXT S Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis ERY I AZM, CLR, RXT I Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis ERY R AZM, CLR, RXT R Moraxella catarrhalis Breakpoints
genus_species is Moraxella catarrhalis TCY S DOX, MNO S Moraxella catarrhalis Breakpoints
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-positives Breakpoints
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-positives Breakpoints
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-positives Breakpoints
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-negatives Breakpoints
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-negatives Breakpoints
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-negatives Breakpoints
genus_species is Pasteurella multocida PEN S AMP, AMX S Pasteurella multocida Breakpoints
genus_species is Pasteurella multocida PEN I AMP, AMX I Pasteurella multocida Breakpoints
genus_species is Pasteurella multocida PEN R AMP, AMX R Pasteurella multocida Breakpoints
genus_species is Campylobacter coli ERY S AZM, CLR S Campylobacter coli Breakpoints
genus_species is Campylobacter coli ERY I AZM, CLR I Campylobacter coli Breakpoints
genus_species is Campylobacter coli ERY R AZM, CLR R Campylobacter coli Breakpoints
genus_species is Campylobacter coli TCY S DOX S Campylobacter coli Breakpoints
genus_species is Campylobacter coli TCY I DOX I Campylobacter coli Breakpoints
genus_species is Campylobacter coli TCY R DOX R Campylobacter coli Breakpoints
genus_species is Campylobacter jejuni ERY S AZM, CLR S Campylobacter jejuni Breakpoints
genus_species is Campylobacter jejuni ERY I AZM, CLR I Campylobacter jejuni Breakpoints
genus_species is Campylobacter jejuni ERY R AZM, CLR R Campylobacter jejuni Breakpoints
genus_species is Campylobacter jejuni TCY S DOX S Campylobacter jejuni Breakpoints
genus_species is Campylobacter jejuni TCY I DOX I Campylobacter jejuni Breakpoints
genus_species is Campylobacter jejuni TCY R DOX R Campylobacter jejuni Breakpoints
genus_species is Aerococcus sanguinicola NOR S fluoroquinolones S Aerococcus sanguinicola Breakpoints
genus_species is Aerococcus sanguinicola NOR I fluoroquinolones I Aerococcus sanguinicola Breakpoints
genus_species is Aerococcus sanguinicola NOR R fluoroquinolones R Aerococcus sanguinicola Breakpoints
genus_species is Aerococcus sanguinicola CIP S LVX S Aerococcus sanguinicola Breakpoints
genus_species is Aerococcus sanguinicola CIP I LVX I Aerococcus sanguinicola Breakpoints
genus_species is Aerococcus sanguinicola CIP R LVX R Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae NOR S fluoroquinolones S Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae NOR I fluoroquinolones I Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae NOR R fluoroquinolones R Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae CIP S LVX S Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae CIP I LVX I Aerococcus urinae Breakpoints
genus_species is Aerococcus urinae CIP R LVX R Aerococcus urinae Breakpoints
genus_species is Kingella kingae PEN S AMP, AMX S Kingella kingae Breakpoints
genus_species is Kingella kingae PEN I AMP, AMX I Kingella kingae Breakpoints
genus_species is Kingella kingae PEN R AMP, AMX R Kingella kingae Breakpoints
genus_species is Kingella kingae ERY S AZM, CLR S Kingella kingae Breakpoints
genus_species is Kingella kingae ERY I AZM, CLR I Kingella kingae Breakpoints
genus_species is Kingella kingae ERY R AZM, CLR R Kingella kingae Breakpoints
genus_species is Kingella kingae TCY S DOX S Kingella kingae Breakpoints
genus_species is Kingella kingae TCY I DOX I Kingella kingae Breakpoints
genus_species is Kingella kingae TCY R DOX R Kingella kingae Breakpoints
genus_species is Burkholderia pseudomallei TCY S DOX S Burkholderia pseudomallei Breakpoints
genus_species is Burkholderia pseudomallei TCY I DOX I Burkholderia pseudomallei Breakpoints
genus_species is Burkholderia pseudomallei TCY R DOX R Burkholderia pseudomallei Breakpoints
order is Enterobacterales PEN, glycopeptides, FUS, macrolides, LIN, streptogramins, RIF, DAP, LNZ R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
fullname like ^Citrobacter (koseri|amalonaticus|sedlakii|farmeri|rodentium) aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
fullname like ^Citrobacter (freundii|braakii|murliniae|werkmanii|youngae) aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Enterobacter cloacae aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Enterobacter aerogenes aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Escherichia hermanni aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Hafnia alvei aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus is Klebsiella aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Morganella morganii aminopenicillins, AMC, CZO, tetracyclines, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Proteus mirabilis tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Proteus penneri aminopenicillins, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Proteus vulgaris aminopenicillins, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Providencia rettgeri aminopenicillins, AMC, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Providencia stuartii aminopenicillins, AMC, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus is Raoultella aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Serratia marcescens aminopenicillins, AMC, CZO, FOX, CXM, DOX, TCY, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Yersinia enterocolitica aminopenicillins, AMC, TIC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus_species is Yersinia pseudotuberculosis PLB, COL R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules
genus one_of Achromobacter, Acinetobacter, Alcaligenes, Bordatella, Burkholderia, Elizabethkingia, Flavobacterium, Ochrobactrum, Pseudomonas, Stenotrophomonas PEN, FOX, CXM, glycopeptides, FUS, macrolides, LIN, streptogramins, RIF, DAP, LNZ R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Acinetobacter baumannii aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Acinetobacter pittii aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Acinetobacter nosocomialis aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Acinetobacter calcoaceticus aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Achromobacter xylosoxidans aminopenicillins, CZO, CTX, CRO, ETP R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
fullname like ^Burkholderia (ambifaria|anthina|arboris|cepacia|cenocepacia|contaminans|diffusa|dolosa|lata|latens|metallica|multivorans|paludis|pseudomultivorans|pyrrocinia|pseudomultivorans|seminalis|stabilis|stagnalis|territorii|ubonensis|vietnamiensis) aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, ATM, ETP, CIP, CHL, aminoglycosides, TMP, FOS, polymyxins R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Elizabethkingia meningoseptica aminopenicillins, AMC, TIC, CZO, CTX, CRO, CAZ, FEP, ATM, ETP, IPM, MEM, polymyxins R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Ochrobactrum anthropi aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, CAZ, FEP, ATM, ETP R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Pseudomonas aeruginosa aminopenicillins, AMC, CZO, CTX, CRO, ETP, CHL, KAN, NEO, TMP, SXT, tetracyclines, TGC R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus_species is Stenotrophomonas maltophilia aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, ATM, ETP, IPM, MEM, aminoglycosides, TMP, FOS, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules
genus one_of Haemophilus, Moraxella, Neisseria, Campylobacter glycopeptides, LIN, DAP, LNZ R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus_species is Haemophilus influenzae FUS, streptogramins R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus_species is Moraxella catarrhalis TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus is Neisseria TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus_species is Campylobacter fetus FUS, streptogramins, TMP, NAL R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus_species is Campylobacter jejuni FUS, streptogramins, TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
genus_species is Campylobacter coli FUS, streptogramins, TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules
gramstain is Gram-positive ATM, polymyxins, NAL R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus saprophyticus FUS, CAZ, FOS, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus cohnii CAZ, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus xylosus CAZ, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus capitis CAZ, FOS R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus aureus CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus epidermidis CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus coagulase-negative CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus hominis CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus haemolyticus CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus intermedius CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Staphylococcus pseudintermedius CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus is Streptococcus FUS, CAZ, aminoglycosides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Enterococcus faecalis FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Enterococcus gallinarum FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, VAN, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Enterococcus casseliflavus FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, VAN, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Enterococcus faecium FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus is Corynebacterium FOS R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Listeria monocytogenes cephalosporins R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus one_of Leuconostoc, Pediococcus glycopeptides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus is Lactobacillus glycopeptides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Clostridium ramosum VAN R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species is Clostridium innocuum VAN R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules
genus_species like ^Streptococcus (pyogenes|agalactiae|dysgalactiae|group A|group B|group C|group G) PEN S aminopenicillins, cephalosporins_except_CAZ, carbapenems S Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules
genus is Enterococcus AMP R ureidopenicillins, carbapenems R Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules
genus is Enterococcus AMX R ureidopenicillins, carbapenems R Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules
order is Enterobacterales TIC, PIP R, S PIP R Table 09: Interpretive rules for B-lactam agents and Gram-negative rods (at the time: Enterobacteriaceae) Expert Rules
genus like .* ERY S AZM, CLR S Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules
genus like .* ERY I AZM, CLR I Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules
genus like .* ERY R AZM, CLR R Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules
genus is Staphylococcus TOB R KAN, AMK R Table 12: Interpretive rules for aminoglycosides Expert Rules
genus is Staphylococcus GEN R aminoglycosides R Table 12: Interpretive rules for aminoglycosides Expert Rules
order is Enterobacterales GEN, TOB I, S GEN R Table 12: Interpretive rules for aminoglycosides Expert Rules
order is Enterobacterales GEN, TOB R, I TOB R Table 12: Interpretive rules for aminoglycosides Expert Rules
genus is Staphylococcus MFX R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules
genus_species is Streptococcus pneumoniae MFX R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules
order is Enterobacterales CIP R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules
genus_species is Neisseria gonorrhoeae CIP R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules
# -------------------------------------------------------------------------------------------------------------------------------
if_mo_property like.is.one_of this_value and_these_antibiotics have_these_values then_change_these_antibiotics to_value reference.rule reference.rule_group reference.version note
order is Enterobacterales AMP S AMX S Enterobacterales (Order) Breakpoints 10
order is Enterobacterales AMP I AMX I Enterobacterales (Order) Breakpoints 10
order is Enterobacterales AMP R AMX R Enterobacterales (Order) Breakpoints 10
genus is Staphylococcus PEN, FOX S AMP, AMX, PIP, TIC S Staphylococcus Breakpoints 10
genus is Staphylococcus PEN, FOX R, S OXA, FLC S Staphylococcus Breakpoints 10
genus is Staphylococcus FOX R all_betalactams R Staphylococcus Breakpoints 10
genus_species is Staphylococcus saprophyticus AMP S AMX, AMC, PIP, TZP S Staphylococcus Breakpoints 10
genus is Staphylococcus FOX S carbapenems, cephalosporins_except_CAZ S Staphylococcus Breakpoints 10
genus is Staphylococcus FOX I carbapenems, cephalosporins_except_CAZ I Staphylococcus Breakpoints 10
genus is Staphylococcus FOX R carbapenems, cephalosporins_except_CAZ R Staphylococcus Breakpoints 10
genus is Staphylococcus NOR S CIP, LVX, MFX, OFX S Staphylococcus Breakpoints 10
genus is Staphylococcus ERY S AZM, CLR, RXT S Staphylococcus Breakpoints 10
genus is Staphylococcus ERY I AZM, CLR, RXT I Staphylococcus Breakpoints 10
genus is Staphylococcus ERY R AZM, CLR, RXT R Staphylococcus Breakpoints 10
genus is Staphylococcus TCY S DOX, MNO S Staphylococcus Breakpoints 10
genus is Enterococcus AMP S AMX, AMC, PIP, TZP S Enterococcus Breakpoints 10
genus is Enterococcus AMP I AMX, AMC, PIP, TZP I Enterococcus Breakpoints 10
genus is Enterococcus AMP R AMX, AMC, PIP, TZP R Enterococcus Breakpoints 10
genus is Enterococcus NOR S CIP, LVX S Enterococcus Breakpoints 10
genus is Enterococcus NOR I CIP, LVX I Enterococcus Breakpoints 10
genus is Enterococcus NOR R CIP, LVX R Enterococcus Breakpoints 10
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN S aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC S Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN I aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC I Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN R aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC R Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR S MFX S Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR S LVX I Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY S AZM, CLR, RXT S Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY I AZM, CLR, RXT I Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY R AZM, CLR, RXT R Streptococcus groups A, B, C, G Breakpoints 10
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G TCY S DOX, MNO S Streptococcus groups A, B, C, G Breakpoints 10
genus_species is Streptococcus pneumoniae PEN S AMP, AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae AMP S AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae AMP I AMX, AMC, PIP, TZP I Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae AMP R AMX, AMC, PIP, TZP R Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae NOR S MFX S Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae NOR S LVX I Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae ERY S AZM, CLR, RXT S Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae ERY I AZM, CLR, RXT I Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae ERY R AZM, CLR, RXT R Streptococcus pneumoniae Breakpoints 10
genus_species is Streptococcus pneumoniae TCY S DOX, MNO S Streptococcus pneumoniae Breakpoints 10
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ PEN S AMP, AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints 10
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP S AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints 10
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP I AMX, AMC, PIP, TZP I Viridans group streptococci Breakpoints 10
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP R AMX, AMC, PIP, TZP R Viridans group streptococci Breakpoints 10
genus_species is Haemophilus influenzae AMP S AMX, PIP S Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae AMP I AMX, PIP I Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae AMP R AMX, PIP R Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae PEN S AMP, AMX, AMC, PIP, TZP S Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae AMC S TZP S Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae AMC I TZP I Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae AMC R TZP R Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae NAL S CIP, LVX, MFX, OFX S Haemophilus influenzae Breakpoints 10
genus_species is Haemophilus influenzae TCY S DOX, MNO S Haemophilus influenzae Breakpoints 10
genus_species is Moraxella catarrhalis AMC S TZP S Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis AMC I TZP I Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis AMC R TZP R Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis NAL S CIP, LVX, MFX, OFX S Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis ERY S AZM, CLR, RXT S Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis ERY I AZM, CLR, RXT I Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis ERY R AZM, CLR, RXT R Moraxella catarrhalis Breakpoints 10
genus_species is Moraxella catarrhalis TCY S DOX, MNO S Moraxella catarrhalis Breakpoints 10
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-positives Breakpoints 10
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-positives Breakpoints 10
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-positives Breakpoints 10
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-negatives Breakpoints 10
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-negatives Breakpoints 10
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-negatives Breakpoints 10
genus_species is Pasteurella multocida PEN S AMP, AMX S Pasteurella multocida Breakpoints 10
genus_species is Pasteurella multocida PEN I AMP, AMX I Pasteurella multocida Breakpoints 10
genus_species is Pasteurella multocida PEN R AMP, AMX R Pasteurella multocida Breakpoints 10
genus_species is Campylobacter coli ERY S AZM, CLR S Campylobacter coli Breakpoints 10
genus_species is Campylobacter coli ERY I AZM, CLR I Campylobacter coli Breakpoints 10
genus_species is Campylobacter coli ERY R AZM, CLR R Campylobacter coli Breakpoints 10
genus_species is Campylobacter coli TCY S DOX S Campylobacter coli Breakpoints 10
genus_species is Campylobacter coli TCY I DOX I Campylobacter coli Breakpoints 10
genus_species is Campylobacter coli TCY R DOX R Campylobacter coli Breakpoints 10
genus_species is Campylobacter jejuni ERY S AZM, CLR S Campylobacter jejuni Breakpoints 10
genus_species is Campylobacter jejuni ERY I AZM, CLR I Campylobacter jejuni Breakpoints 10
genus_species is Campylobacter jejuni ERY R AZM, CLR R Campylobacter jejuni Breakpoints 10
genus_species is Campylobacter jejuni TCY S DOX S Campylobacter jejuni Breakpoints 10
genus_species is Campylobacter jejuni TCY I DOX I Campylobacter jejuni Breakpoints 10
genus_species is Campylobacter jejuni TCY R DOX R Campylobacter jejuni Breakpoints 10
genus_species is Aerococcus sanguinicola NOR S fluoroquinolones S Aerococcus sanguinicola Breakpoints 10
genus_species is Aerococcus sanguinicola NOR I fluoroquinolones I Aerococcus sanguinicola Breakpoints 10
genus_species is Aerococcus sanguinicola NOR R fluoroquinolones R Aerococcus sanguinicola Breakpoints 10
genus_species is Aerococcus sanguinicola CIP S LVX S Aerococcus sanguinicola Breakpoints 10
genus_species is Aerococcus sanguinicola CIP I LVX I Aerococcus sanguinicola Breakpoints 10
genus_species is Aerococcus sanguinicola CIP R LVX R Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae NOR S fluoroquinolones S Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae NOR I fluoroquinolones I Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae NOR R fluoroquinolones R Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae CIP S LVX S Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae CIP I LVX I Aerococcus urinae Breakpoints 10
genus_species is Aerococcus urinae CIP R LVX R Aerococcus urinae Breakpoints 10
genus_species is Kingella kingae PEN S AMP, AMX S Kingella kingae Breakpoints 10
genus_species is Kingella kingae PEN I AMP, AMX I Kingella kingae Breakpoints 10
genus_species is Kingella kingae PEN R AMP, AMX R Kingella kingae Breakpoints 10
genus_species is Kingella kingae ERY S AZM, CLR S Kingella kingae Breakpoints 10
genus_species is Kingella kingae ERY I AZM, CLR I Kingella kingae Breakpoints 10
genus_species is Kingella kingae ERY R AZM, CLR R Kingella kingae Breakpoints 10
genus_species is Kingella kingae TCY S DOX S Kingella kingae Breakpoints 10
genus_species is Kingella kingae TCY I DOX I Kingella kingae Breakpoints 10
genus_species is Kingella kingae TCY R DOX R Kingella kingae Breakpoints 10
genus_species is Burkholderia pseudomallei TCY S DOX S Burkholderia pseudomallei Breakpoints 10
genus_species is Burkholderia pseudomallei TCY I DOX I Burkholderia pseudomallei Breakpoints 10
genus_species is Burkholderia pseudomallei TCY R DOX R Burkholderia pseudomallei Breakpoints 10
order is Enterobacterales AMP S AMX S Enterobacterales (Order) Breakpoints 11
order is Enterobacterales AMP I AMX I Enterobacterales (Order) Breakpoints 11
order is Enterobacterales AMP R AMX R Enterobacterales (Order) Breakpoints 11
genus is Staphylococcus PEN, FOX S AMP, AMX, PIP, TIC S Staphylococcus Breakpoints 11
genus is Staphylococcus PEN, FOX R, S OXA, FLC S Staphylococcus Breakpoints 11
genus is Staphylococcus FOX R all_betalactams R Staphylococcus Breakpoints 11
genus_species is Staphylococcus saprophyticus AMP S AMX, AMC, PIP, TZP S Staphylococcus Breakpoints 11
genus is Staphylococcus FOX S carbapenems, cephalosporins_except_CAZ S Staphylococcus Breakpoints 11
genus is Staphylococcus FOX I carbapenems, cephalosporins_except_CAZ I Staphylococcus Breakpoints 11
genus is Staphylococcus FOX R carbapenems, cephalosporins_except_CAZ R Staphylococcus Breakpoints 11
genus is Staphylococcus NOR S CIP, LVX, MFX, OFX S Staphylococcus Breakpoints 11
genus is Staphylococcus ERY S AZM, CLR, RXT S Staphylococcus Breakpoints 11
genus is Staphylococcus ERY I AZM, CLR, RXT I Staphylococcus Breakpoints 11
genus is Staphylococcus ERY R AZM, CLR, RXT R Staphylococcus Breakpoints 11
genus is Staphylococcus TCY S DOX, MNO S Staphylococcus Breakpoints 11
genus is Enterococcus AMP S AMX, AMC, PIP, TZP S Enterococcus Breakpoints 11
genus is Enterococcus AMP I AMX, AMC, PIP, TZP I Enterococcus Breakpoints 11
genus is Enterococcus AMP R AMX, AMC, PIP, TZP R Enterococcus Breakpoints 11
genus is Enterococcus NOR S CIP, LVX S Enterococcus Breakpoints 11
genus is Enterococcus NOR I CIP, LVX I Enterococcus Breakpoints 11
genus is Enterococcus NOR R CIP, LVX R Enterococcus Breakpoints 11
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN S aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC S Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN I aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC I Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN R aminopenicillins, ureidopenicillins, cephalosporins_except_CAZ, carbapenems, FLC, AMC R Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR S MFX S Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR S LVX I Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY S AZM, CLR, RXT S Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY I AZM, CLR, RXT I Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G ERY R AZM, CLR, RXT R Streptococcus groups A, B, C, G Breakpoints 11
genus_species like Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G TCY S DOX, MNO S Streptococcus groups A, B, C, G Breakpoints 11
genus_species is Streptococcus pneumoniae PEN S AMP, AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae AMP S AMX, AMC, PIP, TZP S Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae AMP I AMX, AMC, PIP, TZP I Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae AMP R AMX, AMC, PIP, TZP R Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae NOR S MFX S Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae NOR S LVX I Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae ERY S AZM, CLR, RXT S Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae ERY I AZM, CLR, RXT I Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae ERY R AZM, CLR, RXT R Streptococcus pneumoniae Breakpoints 11
genus_species is Streptococcus pneumoniae TCY S DOX, MNO S Streptococcus pneumoniae Breakpoints 11
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ PEN S AMP, AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints 11
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP S AMX, AMC, PIP, TZP S Viridans group streptococci Breakpoints 11
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP I AMX, AMC, PIP, TZP I Viridans group streptococci Breakpoints 11
genus_species like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ AMP R AMX, AMC, PIP, TZP R Viridans group streptococci Breakpoints 11
genus_species is Haemophilus influenzae AMP S AMX, PIP S Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae AMP I AMX, PIP I Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae AMP R AMX, PIP R Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae PEN S AMP, AMX, AMC, PIP, TZP S Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae AMC S TZP S Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae AMC I TZP I Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae AMC R TZP R Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae NAL S CIP, LVX, MFX, OFX S Haemophilus influenzae Breakpoints 11
genus_species is Haemophilus influenzae TCY S DOX, MNO S Haemophilus influenzae Breakpoints 11
genus_species is Moraxella catarrhalis AMC S TZP S Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis AMC I TZP I Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis AMC R TZP R Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis NAL S CIP, LVX, MFX, OFX S Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis ERY S AZM, CLR, RXT S Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis ERY I AZM, CLR, RXT I Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis ERY R AZM, CLR, RXT R Moraxella catarrhalis Breakpoints 11
genus_species is Moraxella catarrhalis TCY S DOX, MNO S Moraxella catarrhalis Breakpoints 11
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-positives Breakpoints 11
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-positives Breakpoints 11
genus one_of Actinomyces, Bifidobacterium, Clostridium, Cutibacterium, Eggerthella, Eubacterium, Lactobacillus, Propionibacterium PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-positives Breakpoints 11
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN S AMP, AMX, PIP, TZP, TIC S Anaerobic Gram-negatives Breakpoints 11
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN I AMP, AMX, PIP, TZP, TIC I Anaerobic Gram-negatives Breakpoints 11
genus one_of Bacteroides, Bilophila , Fusobacterium, Mobiluncus, Porphyromonas, Prevotella PEN R AMP, AMX, PIP, TZP, TIC R Anaerobic Gram-negatives Breakpoints 11
genus_species is Pasteurella multocida PEN S AMP, AMX S Pasteurella multocida Breakpoints 11
genus_species is Pasteurella multocida PEN I AMP, AMX I Pasteurella multocida Breakpoints 11
genus_species is Pasteurella multocida PEN R AMP, AMX R Pasteurella multocida Breakpoints 11
genus_species is Campylobacter coli ERY S AZM, CLR S Campylobacter coli Breakpoints 11
genus_species is Campylobacter coli ERY I AZM, CLR I Campylobacter coli Breakpoints 11
genus_species is Campylobacter coli ERY R AZM, CLR R Campylobacter coli Breakpoints 11
genus_species is Campylobacter coli TCY S DOX S Campylobacter coli Breakpoints 11
genus_species is Campylobacter coli TCY I DOX I Campylobacter coli Breakpoints 11
genus_species is Campylobacter coli TCY R DOX R Campylobacter coli Breakpoints 11
genus_species is Campylobacter jejuni ERY S AZM, CLR S Campylobacter jejuni Breakpoints 11
genus_species is Campylobacter jejuni ERY I AZM, CLR I Campylobacter jejuni Breakpoints 11
genus_species is Campylobacter jejuni ERY R AZM, CLR R Campylobacter jejuni Breakpoints 11
genus_species is Campylobacter jejuni TCY S DOX S Campylobacter jejuni Breakpoints 11
genus_species is Campylobacter jejuni TCY I DOX I Campylobacter jejuni Breakpoints 11
genus_species is Campylobacter jejuni TCY R DOX R Campylobacter jejuni Breakpoints 11
genus_species is Aerococcus sanguinicola NOR S fluoroquinolones S Aerococcus sanguinicola Breakpoints 11
genus_species is Aerococcus sanguinicola NOR I fluoroquinolones I Aerococcus sanguinicola Breakpoints 11
genus_species is Aerococcus sanguinicola NOR R fluoroquinolones R Aerococcus sanguinicola Breakpoints 11
genus_species is Aerococcus sanguinicola CIP S LVX S Aerococcus sanguinicola Breakpoints 11
genus_species is Aerococcus sanguinicola CIP I LVX I Aerococcus sanguinicola Breakpoints 11
genus_species is Aerococcus sanguinicola CIP R LVX R Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae NOR S fluoroquinolones S Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae NOR I fluoroquinolones I Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae NOR R fluoroquinolones R Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae CIP S LVX S Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae CIP I LVX I Aerococcus urinae Breakpoints 11
genus_species is Aerococcus urinae CIP R LVX R Aerococcus urinae Breakpoints 11
genus_species is Kingella kingae PEN S AMP, AMX S Kingella kingae Breakpoints 11
genus_species is Kingella kingae PEN I AMP, AMX I Kingella kingae Breakpoints 11
genus_species is Kingella kingae PEN R AMP, AMX R Kingella kingae Breakpoints 11
genus_species is Kingella kingae ERY S AZM, CLR S Kingella kingae Breakpoints 11
genus_species is Kingella kingae ERY I AZM, CLR I Kingella kingae Breakpoints 11
genus_species is Kingella kingae ERY R AZM, CLR R Kingella kingae Breakpoints 11
genus_species is Kingella kingae TCY S DOX S Kingella kingae Breakpoints 11
genus_species is Kingella kingae TCY I DOX I Kingella kingae Breakpoints 11
genus_species is Kingella kingae TCY R DOX R Kingella kingae Breakpoints 11
genus_species is Burkholderia pseudomallei TCY S DOX S Burkholderia pseudomallei Breakpoints 11
genus_species is Burkholderia pseudomallei TCY I DOX I Burkholderia pseudomallei Breakpoints 11
genus_species is Burkholderia pseudomallei TCY R DOX R Burkholderia pseudomallei Breakpoints 11
genus is Bacillus NOR S fluoroquinolones S Bacillus Breakpoints 11 added in 11
genus is Bacillus NOR I fluoroquinolones I Bacillus Breakpoints 11 added in 11
genus is Bacillus NOR R fluoroquinolones R Bacillus Breakpoints 11 added in 11
order is Enterobacterales PEN, glycopeptides, FUS, macrolides, LIN, streptogramins, RIF, DAP, LNZ R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
fullname like ^Citrobacter (koseri|amalonaticus|sedlakii|farmeri|rodentium) aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
fullname like ^Citrobacter (freundii|braakii|murliniae|werkmanii|youngae) aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Enterobacter cloacae aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Klebsiella aerogenes aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1 originally Enterobacter aerogenes, but was renamed to Klebsiella aerogenes
genus_species is Escherichia hermannii aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Hafnia alvei aminopenicillins, AMC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus is Klebsiella aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Morganella morganii aminopenicillins, AMC, CZO, tetracyclines, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Proteus mirabilis tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Proteus penneri aminopenicillins, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Proteus vulgaris aminopenicillins, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Providencia rettgeri aminopenicillins, AMC, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Providencia stuartii aminopenicillins, AMC, CZO, CXM, tetracyclines, TGC, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus is Raoultella aminopenicillins, TIC R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Serratia marcescens aminopenicillins, AMC, CZO, FOX, CXM, DOX, TCY, polymyxins, NIT R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Yersinia enterocolitica aminopenicillins, AMC, TIC, CZO, FOX R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus_species is Yersinia pseudotuberculosis PLB, COL R Table 01: Intrinsic resistance in Enterobacterales (at the time: Enterobacteriaceae) Expert Rules 3.1
genus one_of Achromobacter, Acinetobacter, Alcaligenes, Bordetella, Burkholderia, Elizabethkingia, Flavobacterium, Ochrobactrum, Pseudomonas, Stenotrophomonas PEN, FOX, CXM, glycopeptides, FUS, macrolides, LIN, streptogramins, RIF, DAP, LNZ R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Acinetobacter baumannii aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Acinetobacter pittii aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Acinetobacter nosocomialis aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Acinetobacter calcoaceticus aminopenicillins, AMC, CZO, CTX, CRO, ATM, ETP, TMP, FOS, DOX, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Achromobacter xylosoxidans aminopenicillins, CZO, CTX, CRO, ETP R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
fullname like ^Burkholderia (ambifaria|anthina|arboris|cepacia|cenocepacia|contaminans|diffusa|dolosa|lata|latens|metallica|multivorans|paludis|pseudomultivorans|pyrrocinia|pseudomultivorans|seminalis|stabilis|stagnalis|territorii|ubonensis|vietnamiensis) aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, ATM, ETP, CIP, CHL, aminoglycosides, TMP, FOS, polymyxins R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Elizabethkingia meningoseptica aminopenicillins, AMC, TIC, CZO, CTX, CRO, CAZ, FEP, ATM, ETP, IPM, MEM, polymyxins R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Ochrobactrum anthropi aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, CAZ, FEP, ATM, ETP R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Pseudomonas aeruginosa aminopenicillins, AMC, CZO, CTX, CRO, ETP, CHL, KAN, NEO, TMP, SXT, tetracyclines, TGC R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus_species is Stenotrophomonas maltophilia aminopenicillins, AMC, TIC, PIP, TZP, CZO, CTX, CRO, ATM, ETP, IPM, MEM, aminoglycosides, TMP, FOS, TCY R Table 02: Intrinsic resistance in non-fermentative Gram-negative bacteria Expert Rules 3.1
genus one_of Haemophilus, Moraxella, Neisseria, Campylobacter glycopeptides, LIN, DAP, LNZ R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus_species is Haemophilus influenzae FUS, streptogramins R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus_species is Moraxella catarrhalis TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus is Neisseria TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus_species is Campylobacter fetus FUS, streptogramins, TMP, NAL R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus_species is Campylobacter jejuni FUS, streptogramins, TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
genus_species is Campylobacter coli FUS, streptogramins, TMP R Table 03: Intrinsic resistance in other Gram-negative bacteria Expert Rules 3.1
gramstain is Gram-positive ATM, polymyxins, NAL R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus saprophyticus FUS, CAZ, FOS, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus cohnii CAZ, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus xylosus CAZ, NOV R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus capitis CAZ, FOS R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus aureus CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus epidermidis CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus coagulase-negative CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus hominis CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus haemolyticus CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus intermedius CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Staphylococcus pseudintermedius CAZ R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus is Streptococcus FUS, CAZ, aminoglycosides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Enterococcus faecalis FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Enterococcus gallinarum FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, VAN, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Enterococcus casseliflavus FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, VAN, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Enterococcus faecium FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, TMP, SXT R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus is Corynebacterium FOS R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Listeria monocytogenes cephalosporins R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus one_of Leuconostoc, Pediococcus glycopeptides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus is Lactobacillus glycopeptides R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Clostridium ramosum VAN R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species is Clostridium innocuum VAN R Table 04: Intrinsic resistance in Gram-positive bacteria Expert Rules 3.1
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN S aminopenicillins, cephalosporins_except_CAZ, carbapenems S Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules 3.1
genus is Enterococcus AMP R ureidopenicillins, carbapenems R Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules 3.1
genus is Enterococcus AMX R ureidopenicillins, carbapenems R Table 08: Interpretive rules for B-lactam agents and Gram-positive cocci Expert Rules 3.1
order is Enterobacterales TIC, PIP R, S PIP R Table 09: Interpretive rules for B-lactam agents and Gram-negative rods (at the time: Enterobacteriaceae) Expert Rules 3.1
genus like .* ERY S AZM, CLR S Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules 3.1
genus like .* ERY I AZM, CLR I Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules 3.1
genus like .* ERY R AZM, CLR R Table 11: Interpretive rules for macrolides, lincosamides, and streptogramins Expert Rules 3.1
genus is Staphylococcus TOB R KAN, AMK R Table 12: Interpretive rules for aminoglycosides Expert Rules 3.1
genus is Staphylococcus GEN R aminoglycosides R Table 12: Interpretive rules for aminoglycosides Expert Rules 3.1
order is Enterobacterales GEN, TOB I, S GEN R Table 12: Interpretive rules for aminoglycosides Expert Rules 3.1
order is Enterobacterales GEN, TOB R, I TOB R Table 12: Interpretive rules for aminoglycosides Expert Rules 3.1
genus is Staphylococcus MFX R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules 3.1
genus_species is Streptococcus pneumoniae MFX R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules 3.1
order is Enterobacterales CIP R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules 3.1
genus_species is Neisseria gonorrhoeae CIP R fluoroquinolones R Table 13: Interpretive rules for quinolones Expert Rules 3.1
order is Enterobacterales PEN, glycopeptides, lipoglycopeptides, FUS, macrolides, lincosamides, streptogramins, RIF, oxazolidinones R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
fullname like ^Citrobacter (koseri|amalonaticus|sedlakii|farmeri|rodentium) aminopenicillins, TIC R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
fullname like ^Citrobacter (freundii|braakii|murliniae|werkmanii|youngae) aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Enterobacter cloacae aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Escherichia hermannii aminopenicillins, TIC R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Hafnia alvei aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, FOX, polymyxins R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Klebsiella aerogenes aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Klebsiella oxytoca aminopenicillins, TIC R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
fullname like ^Klebsiella( pneumoniae| quasipneumoniae| variicola)? aminopenicillins, TIC R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Leclercia adecarboxylata FOS R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Morganella morganii aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, tetracyclines, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Plesiomonas shigelloides aminopenicillins, AMC, SAM R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Proteus mirabilis tetracyclines, TGC, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Proteus penneri aminopenicillins, CZO, CEP, LEX, CFR, CXM, tetracyclines, TGC, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Proteus vulgaris aminopenicillins, CZO, CEP, LEX, CFR, CXM, tetracyclines, TGC, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Providencia rettgeri aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, tetracyclines, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Providencia stuartii aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, tetracyclines, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus is Raoultella aminopenicillins, TIC R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Serratia marcescens aminopenicillins, AMC, SAM, CZO, CEP, LEX, CFR, FOX, CXM, DOX, TCY, polymyxins, NIT R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Yersinia enterocolitica aminopenicillins, AMC, SAM, TIC, CZO, CEP, LEX, CFR, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Yersinia pseudotuberculosis polymyxins R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Aeromonas hydrophila aminopenicillins, AMC, SAM, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Aeromonas veronii aminopenicillins, AMC, SAM, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Aeromonas dhakensis aminopenicillins, AMC, SAM, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Aeromonas caviae aminopenicillins, AMC, SAM, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus_species is Aeromonas jandaei aminopenicillins, AMC, SAM, TIC, CZO, CEP, LEX, CFR, FOX R Table 1: Intrinsic resistance in Enterobacterales and Aeromonas spp. Expert Rules 3.2
genus one_of Achromobacter, Acinetobacter, Alcaligenes, Bordetella, Burkholderia, Elizabethkingia, Flavobacterium, Ochrobactrum, Pseudomonas, Stenotrophomonas PEN, cephalosporins_1st, cephalosporins_2nd, glycopeptides, lipoglycopeptides, FUS, macrolides, lincosamides, streptogramins, RIF, oxazolidinones R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2
fullname like ^Acinetobacter (baumannii|pittii|nosocomialis) aminopenicillins, AMC, CRO, CTX, ATM, ETP, TMP, FOS, DOX, TCY R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus is Acinetobacter DOX, TCY R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Achromobacter xylosoxidans aminopenicillins, CRO, CTX, ETP R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
fullname like ^Burkholderia (ambifaria|anthina|arboris|cepacia|cenocepacia|contaminans|diffusa|dolosa|lata|latens|metallica|multivorans|paludis|pseudomultivorans|pyrrocinia|pseudomultivorans|seminalis|stabilis|stagnalis|territorii|ubonensis|vietnamiensis) aminopenicillins, AMC, SAM, TIC, TCC, PIP, TZP, CRO, CTX, ATM, ETP, CIP, CHL, aminoglycosides, TMP, FOS, polymyxins R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Elizabethkingia meningoseptica aminopenicillins, AMC, SAM, TIC, TCC, PIP, CZO, CTX, CRO, CAZ, FEP, ATM, ETP, IPM, MEM, polymyxins R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Ochrobactrum anthropi aminopenicillins, AMC, SAM, TIC, TCC, PIP, TZP, CZO, CTX, CRO, CAZ, FEP, ATM, ETP R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Pseudomonas aeruginosa aminopenicillins, AMC, SAM, CTX, CRO, ETP, CHL, KAN, NEO, TMP, tetracyclines, TGC R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Stenotrophomonas maltophilia aminopenicillins, AMC, SAM, TIC, PIP, TZP, CRO, CTX, ATM, ETP, IPM, MEM, aminoglycosides, TMP, FOS, TCY R Table 2: Intrinsic resistance in non-fermentative gram-negative bacteria Expert Rules 3.2 Additional rules from header added in separate rule (genus is one of…)
genus_species is Haemophilus influenzae FUS, streptogramins, glycopeptides, lipoglycopeptides, lincosamides, oxazolidinones R Table 3: Intrinsic resistance in other gram-negative bacteria Expert Rules 3.2
genus_species is Moraxella catarrhalis TMP, glycopeptides, lipoglycopeptides, lincosamides, oxazolidinones R Table 3: Intrinsic resistance in other gram-negative bacteria Expert Rules 3.2
genus is Neisseria TMP, glycopeptides, lipoglycopeptides, lincosamides, oxazolidinones R Table 3: Intrinsic resistance in other gram-negative bacteria Expert Rules 3.2
genus_species is Campylobacter fetus FUS, streptogramins, TMP, NAL, glycopeptides, lipoglycopeptides, lincosamides, oxazolidinones R Table 3: Intrinsic resistance in other gram-negative bacteria Expert Rules 3.2
fullname like ^Campylobacter (jejuni|coli) FUS, streptogramins, TMP, glycopeptides, lipoglycopeptides, lincosamides, oxazolidinones R Table 3: Intrinsic resistance in other gram-negative bacteria Expert Rules 3.2
gramstain is Gram-positive ATM, TEM, polymyxins, NAL R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus saprophyticus FUS, CAZ, FOS, NOV R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus cohnii CAZ, NOV R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus xylosus CAZ, NOV R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus capitis CAZ, FOS R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus aureus CAZ R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Staphylococcus coagulase-negative CAZ R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus is Streptococcus FUS, CAZ, aminoglycosides R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Enterococcus faecalis FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, SDI, SUD, SDM, SLF, SLF1, SLF2, SZO, SLF3, SLF4, SMX, SLF5, SLF6, SLF7, SLF8, SLF9, SLF10, SLF11, SLF12, SUT, SLF13 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 These last ones are all true sulfonamides
genus_species is Enterococcus faecalis TMP S SXT, SLT1, SLT2, SLT3, SLT4, SLT5 S Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus_species is Enterococcus faecalis TMP I SXT, SLT1, SLT2, SLT3, SLT4, SLT5 I Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus_species is Enterococcus faecalis TMP R SXT, SLT1, SLT2, SLT3, SLT4, SLT5 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
fullname like ^Enterococcus (gallinarum|casseliflavus) FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, CLI, QDA, VAN, SDI, SUD, SDM, SLF, SLF1, SLF2, SZO, SLF3, SLF4, SMX, SLF5, SLF6, SLF7, SLF8, SLF9, SLF10, SLF11, SLF12, SUT, SLF13 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 These last ones are all true sulfonamides
fullname like ^Enterococcus (gallinarum|casseliflavus) TMP S SXT, SLT1, SLT2, SLT3, SLT4, SLT5 S Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
fullname like ^Enterococcus (gallinarum|casseliflavus) TMP I SXT, SLT1, SLT2, SLT3, SLT4, SLT5 I Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
fullname like ^Enterococcus (gallinarum|casseliflavus) TMP R SXT, SLT1, SLT2, SLT3, SLT4, SLT5 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus_species is Enterococcus faecium FUS, CAZ, cephalosporins_except_CAZ, aminoglycosides, macrolides, SDI, SUD, SDM, SLF, SLF1, SLF2, SZO, SLF3, SLF4, SMX, SLF5, SLF6, SLF7, SLF8, SLF9, SLF10, SLF11, SLF12, SUT, SLF13 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 These last ones are all true sulfonamides
genus_species is Enterococcus faecium TMP S SXT, SLT1, SLT2, SLT3, SLT4, SLT5 S Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus_species is Enterococcus faecium TMP I SXT, SLT1, SLT2, SLT3, SLT4, SLT5 I Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus_species is Enterococcus faecium TMP R SXT, SLT1, SLT2, SLT3, SLT4, SLT5 R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2 Since R to sulfonamides - TMP result is equal with combinations
genus is Corynebacterium FOS R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species is Listeria monocytogenes CAZ, cephalosporins_except_CAZ R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus one_of Leuconostoc, Pediococcus VAN, TEC R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus is Lactobacillus VAN, TEC R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
fullname like ^Clostridium (ramosum|innocuum) VAN R Table 4: Intrinsic resistance in gram-positive bacteria Expert Rules 3.2
genus_species one_of Escherichia coli, Proteus mirabilis AMP R PIP R Expert Rules on Enterobacterales Expert Rules 3.2
genus_species one_of Escherichia coli, Proteus mirabilis AMP S PIP S Expert Rules on Enterobacterales Expert Rules 3.2
fullname like ^(Klebsiella(?! aerogenes)|Raoultella) PIP R Expert Rules on Enterobacterales Expert Rules 3.2
fullname like ^(Enterobacter|Klebsiella aerogenes|Citrobacter freundii|Serratia|Morganella morganii|Hafnia alvei|Providencia) CXM S CXM, cephalosporins_2nd R Expert Rules on Enterobacterales Expert Rules 3.2
genus one_of Arsenophonus, Biostraticola, Brenneria, Buchnera, Budvicia, Buttiauxella, Cedecea, Citrobacter, Cosenzaea, Cronobacter, Dickeya, Edwardsiella, Enterobacillus, Enterobacter, Erwinia, Escherichia, Ewingella, Franconibacter, Gibbsiella, Hafnia, Izhakiella, Klebsiella, Kluyvera, Kosakonia, Leclercia, Lelliottia, Leminorella, Lonsdalea, Mangrovibacter, Metakosakonia, Mixta, Moellerella, Morganella, Obesumbacterium, Pantoea, Pectobacterium, Phaseolibacter, Photorhabdus, Phytobacter, Plesiomonas, Pluralibacter, Pragia, Proteus, Providencia, Pseudescherichia, Pseudocitrobacter, Rahnella, Raoultella, Rosenbergiella, Rouxiella, Saccharobacter, Samsonia, Serratia, Shigella, Shimwellia, Siccibacter, Sodalis, Tatumella, Thorsellia, Trabulsiella, Wigglesworthia, Xenorhabdus, Yersinia, Yokenella CIP R fluoroquinolones R Expert Rules on Enterobacterales Expert Rules 3.2 This is Enterobacterales except Salmonella spp.
fullname like ^(Serratia|Providencia|Morganella morganii) TGC R Expert Rules on Enterobacterales Expert Rules 3.2
genus is Salmonella cephalosporins_2nd R Expert Rules on Salmonella Expert Rules 3.2
genus is Salmonella aminoglycosides R Expert Rules on Salmonella Expert Rules 3.2
genus is Salmonella PEF R CIP R Expert Rules on Salmonella Expert Rules 3.2
genus_species is Staphylococcus aureus FOX1 R all_betalactams R Expert Rules on Staphylococcus Expert Rules 3.2
genus_species is Staphylococcus aureus FOX1 S all_betalactams S Expert Rules on Staphylococcus Expert Rules 3.2
genus_species one_of Staphylococcus aureus, Staphylococcus lugdunensis PEN R AMP, AMX, AZL, BAM, CRB, CRN, EPC, HET, MEC, MEZ, MTM, PIP, PME, PVM, SBC, TAL, TEM, TIC R Expert Rules on Staphylococcus Expert Rules 3.2 all penicillins without beta-lactamse inhibitor
genus is Staphylococcus ERY, CLI S macrolides, lincosamides S Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus NOR S CIP, LVX, MFX, OFX S Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus LVX R fluoroquinolones R Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus MFX R fluoroquinolones R Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus TCY S DOX, MNO, TGC S Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus TCY R DOX, MNO R Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus VAN S lipoglycopeptides S Expert Rules on Staphylococcus Expert Rules 3.2
genus is Staphylococcus LNZ S TZD S Expert Rules on Staphylococcus Expert Rules 3.2
fullname like ^Enterococcus (faecalis|faecium) AMP R ureidopenicillins, IPM R Expert Rules on Enterococcus Expert Rules 3.2
fullname like ^Enterococcus (faecalis|faecium) AMX R ureidopenicillins, IPM R Expert Rules on Enterococcus Expert Rules 3.2
genus is Enterococcus NOR S CIP, LVX S Expert Rules on Enterococcus Expert Rules 3.2
genus is Enterococcus VAN S lipoglycopeptides S Expert Rules on Enterococcus Expert Rules 3.2
genus_species is Enterococcus faecium CLI R Expert Rules on Enterococcus Expert Rules 3.2
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G PEN S aminopenicillins, cephalosporins, carbapenems S Expert Rules on Streptococcus A, B, C and G Expert Rules 3.2
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR S LVX, MFX S Expert Rules on Streptococcus A, B, C and G Expert Rules 3.2
genus_species one_of Streptococcus group A, Streptococcus group B, Streptococcus group C, Streptococcus group G NOR R LVX, MFX R Expert Rules on Streptococcus A, B, C and G Expert Rules 3.2
genus_species is Streptococcus pneumoniae OXA S PHN, PEN, aminopenicillins, cephalosporins_except_CAZ, carbapenems S Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae NOR S LVX, MFX S Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae NOR R LVX, MFX R Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae LVX R fluoroquinolones R Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae MFX R fluoroquinolones R Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae TCY S DOX, MNO S Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae TCY R DOX, MNO R Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
genus_species is Streptococcus pneumoniae VAN S lipoglycopeptides S Expert Rules on Streptococcus pneumoniae Expert Rules 3.2
fullname like ^Streptococcus (anginosus|australis|bovis|constellatus|cristatus|equinus|gallolyticus|gordonii|infantarius|infantis|intermedius|mitis|mutans|oligofermentans|oralis|parasanguinis|peroris|pseudopneumoniae|salivarius|sanguinis|sinensis|sobrinus|thermophilus|vestibularis|viridans)$ PEN S aminopenicillins, CTX, CRO S Expert Rules on Viridans Group Streptococci Expert Rules 3.2
genus_species is Haemophilus influenzae PEN S all_betalactams S Expert Rules on Haemophilus influenzae Expert Rules 3.2
genus_species is Haemophilus influenzae NAL S fluoroquinolones S Expert Rules on Haemophilus influenzae Expert Rules 3.2
genus_species is Haemophilus influenzae NAL R CIP, LVX, MFX R Expert Rules on Haemophilus influenzae Expert Rules 3.2
genus_species is Haemophilus influenzae TCY S DOX, MNO S Expert Rules on Haemophilus influenzae Expert Rules 3.2
genus_species is Haemophilus influenzae TCY R DOX, MNO R Expert Rules on Haemophilus influenzae Expert Rules 3.2
genus_species is Moraxella catarrhalis NAL S fluoroquinolones S Expert Rules on Moraxella catarrhalis Expert Rules 3.2
genus_species is Moraxella catarrhalis NAL R fluoroquinolones R Expert Rules on Moraxella catarrhalis Expert Rules 3.2
genus is Campylobacter ERY S CLR, AZM S Expert Rules on Campylobacter Expert Rules 3.2
genus_species is Campylobacter ERY R CLR, AZM R Expert Rules on Campylobacter Expert Rules 3.2
fullname like ^(Enterobacter|Klebsiella aerogenes|Citrobacter (braakii|freundii|gillenii|murliniae|rodenticum|sedlakii|werkmanii|youngae)|Hafnia alvei|Serratia|Morganella morganii|Providencia) CTX S CTX, CRO, CAZ Expert Rules on Enterobacterales (AmpC de-repressed cephalosporins) Expert Rules 3.2 This is rule 3 and 4 of EUCAST Expert Rules v3.2 on Enterobacterales, result will be set with the 'ampc_derepressed_cephalosporins' argument
fullname like ^(Enterobacter|Klebsiella aerogenes|Citrobacter (braakii|freundii|gillenii|murliniae|rodenticum|sedlakii|werkmanii|youngae)|Hafnia alvei|Serratia|Morganella morganii|Providencia) CRO S CTX, CRO, CAZ Expert Rules on Enterobacterales (AmpC de-repressed cephalosporins) Expert Rules 3.2 This is rule 3 and 4 of EUCAST Expert Rules v3.2 on Enterobacterales, result will be set with the 'ampc_derepressed_cephalosporins' argument
fullname like ^(Enterobacter|Klebsiella aerogenes|Citrobacter (braakii|freundii|gillenii|murliniae|rodenticum|sedlakii|werkmanii|youngae)|Hafnia alvei|Serratia|Morganella morganii|Providencia) CAZ S CTX, CRO, CAZ Expert Rules on Enterobacterales (AmpC de-repressed cephalosporins) Expert Rules 3.2 This is rule 3 and 4 of EUCAST Expert Rules v3.2 on Enterobacterales, result will be set with the 'ampc_derepressed_cephalosporins' argument
Can't render this file because it contains an unexpected character in line 6 and column 96.

View File

@@ -1,46 +1,150 @@
# ==================================================================== #
# TITLE #
# Antimicrobial Resistance (AMR) Analysis #
# Antimicrobial Resistance (AMR) Analysis for R #
# #
# SOURCE #
# https://github.com/msberends/AMR #
# #
# LICENCE #
# (c) 2018-2020 Berends MS, Luz CF et al. #
# (c) 2018-2021 Berends MS, Luz CF et al. #
# Developed at the University of Groningen, the Netherlands, in #
# collaboration with non-profit organisations Certe Medical #
# Diagnostics & Advice, and University Medical Center Groningen. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# Visit our website for more info: https://msberends.github.io/AMR. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# Run this file to update the package using: -------------------------------
# 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())
# Helper functions --------------------------------------------------------
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", "caeli", "capitis", "caprae",
"carnosus", "chromogenes", "cohnii", "condimenti",
"debuckii", "devriesei", "edaphicus", "epidermidis",
"equorum", "felis", "fleurettii", "gallinarum",
"haemolyticus", "hominis", "jettensis", "kloosii",
"lentus", "lugdunensis", "massiliensis", "microti",
"muscae", "nepalensis", "pasteuri", "petrasii",
"pettenkoferi", "piscifermentans", "pseudoxylosus",
"rostri", "saccharolyticus", "saprophyticus",
"sciuri", "simulans", "stepanovicii", "succinus",
"vitulinus", "warneri", "xylosus")
| (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",
"simiae", "agnetis",
"delphini", "lutrae",
"hyicus", "intermedius",
"pseudintermedius", "pseudointermedius",
"schweitzeri", "argenteus")
| (MO_staph$species == "schleiferi" & MO_staph$subspecies == "coagulans")),
"mo", drop = TRUE]
}
}
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
}
create_MO_lookup <- function() {
MO_lookup <- AMR::microorganisms
MO_lookup$kingdom_index <- NA_real_
MO_lookup[which(MO_lookup$kingdom == "Bacteria" | MO_lookup$mo == "UNKNOWN"), "kingdom_index"] <- 1
MO_lookup[which(MO_lookup$kingdom == "Fungi"), "kingdom_index"] <- 2
MO_lookup[which(MO_lookup$kingdom == "Protozoa"), "kingdom_index"] <- 3
MO_lookup[which(MO_lookup$kingdom == "Archaea"), "kingdom_index"] <- 4
# all the rest
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.
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)
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))
# 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), ]
}
create_MO.old_lookup <- function() {
MO.old_lookup <- AMR::microorganisms.old
MO.old_lookup$fullname_lower <- trimws(gsub("[^.a-z0-9/ \\-]+", "", tolower(trimws(MO.old_lookup$fullname))))
# add a column with only "e coli"-like combinations
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), ]
}
create_intr_resistance <- function() {
# for mo_is_intrinsic_resistant() - saves a lot of time when executed on this vector
paste(AMR::microorganisms[match(AMR::intrinsic_resistant$microorganism, AMR::microorganisms$fullname), "mo", drop = TRUE],
AMR::antibiotics[match(AMR::intrinsic_resistant$antibiotic, AMR::antibiotics$name), "ab", drop = TRUE])
}
# Save internal data sets to R/sysdata.rda --------------------------------
# See 'data-raw/eucast_rules.tsv' for the EUCAST reference file
eucast_rules_file <- 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
eucast_rules_file$reference.rule_group <- factor(eucast_rules_file$reference.rule_group,
levels = unique(eucast_rules_file$reference.rule_group),
ordered = TRUE)
eucast_rules_file <- dplyr::arrange(eucast_rules_file,
reference.rule_group,
reference.rule)
eucast_rules_file$reference.rule_group <- as.character(eucast_rules_file$reference.rule_group)
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
translations_file <- utils::read.delim(file = "data-raw/translations.tsv",
sep = "\t",
stringsAsFactors = FALSE,
@@ -54,30 +158,133 @@ translations_file <- utils::read.delim(file = "data-raw/translations.tsv",
allowEscapes = TRUE, # else "\\1" will be imported as "\\\\1"
quote = "")
# Old microorganism codes -------------------------------------------------
# Old microorganism codes
microorganisms.translation <- readRDS("data-raw/microorganisms.translation.rds")
# for mo_is_intrinsic_resistant() - saves a lot of time when executed on this vector
INTRINSIC_R <- create_intr_resistance()
# for checking input in `language` argument in e.g. mo_*() and ab_*() functions
LANGUAGES_SUPPORTED <- sort(c("en", unique(translations_file$lang)))
# vectors of CoNS and CoPS, improves speed in as.mo()
MO_CONS <- create_species_cons_cops("CoNS")
MO_COPS <- create_species_cons_cops("CoPS")
# reference data - they have additional columns compared to `antibiotics` and `microorganisms` to improve speed
AB_lookup <- create_AB_lookup()
MO_lookup <- create_MO_lookup()
MO.old_lookup <- create_MO.old_lookup()
# Export to package as internal data ----
usethis::use_data(eucast_rules_file, translations_file, microorganisms.translation,
usethis::use_data(eucast_rules_file,
translations_file,
microorganisms.translation,
INTRINSIC_R,
LANGUAGES_SUPPORTED,
MO_CONS,
MO_COPS,
AB_lookup,
MO_lookup,
MO.old_lookup,
internal = TRUE,
overwrite = TRUE,
version = 2)
version = 2,
compress = "xz")
# Remove from global environment ----
rm(eucast_rules_file)
rm(translations_file)
rm(microorganisms.translation)
# Export data sets to the repository in different formats -----------------
# Save to raw data to repository ----
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)
}
usethis::ui_done(paste0("Saving raw data to {usethis::ui_value('/data-raw/')}"))
devtools::load_all(quiet = TRUE)
# give official names to ABs and MOs
write.table(dplyr::mutate(rsi_translation, ab = ab_name(ab), mo = mo_name(mo)),
"data-raw/rsi_translation.txt", sep = "\t", na = "", row.names = FALSE)
write.table(dplyr::mutate_if(microorganisms, ~!is.numeric(.), as.character),
"data-raw/microorganisms.txt", sep = "\t", na = "", row.names = FALSE)
write.table(dplyr::mutate_if(antibiotics, ~!is.numeric(.), as.character),
"data-raw/antibiotics.txt", sep = "\t", na = "", row.names = FALSE)
write.table(dplyr::mutate_all(antivirals, as.character),
"data-raw/antivirals.txt", sep = "\t", na = "", row.names = FALSE)
rsi <- dplyr::mutate(rsi_translation, ab = ab_name(ab), mo = mo_name(mo))
if (changed_md5(rsi)) {
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)) {
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(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)
}
if (changed_md5(microorganisms.old)) {
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)) {
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)) {
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)
}
if (changed_md5(intrinsic_resistant)) {
write_md5(intrinsic_resistant)
try(saveRDS(intrinsic_resistant, "data-raw/intrinsic_resistant.rds", version = 2, compress = "xz"), silent = TRUE)
try(write.table(intrinsic_resistant, "data-raw/intrinsic_resistant.txt", sep = "\t", na = "", row.names = FALSE), silent = TRUE)
try(haven::write_sas(intrinsic_resistant, "data-raw/intrinsic_resistant.sas"), silent = TRUE)
try(haven::write_sav(intrinsic_resistant, "data-raw/intrinsic_resistant.sav"), silent = TRUE)
try(haven::write_dta(intrinsic_resistant, "data-raw/intrinsic_resistant.dta"), silent = TRUE)
try(openxlsx::write.xlsx(intrinsic_resistant, "data-raw/intrinsic_resistant.xlsx"), silent = TRUE)
}
if (changed_md5(dosage)) {
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)

Binary file not shown.

View File

@@ -0,0 +1 @@
b6de75043ef27eabd6fff22f04638225

Binary file not shown.

Binary file not shown.

Binary file not shown.

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