<<< 1. DATA HANDLING >>>¶

installing packages¶

In [ ]:
install.packages(
    c(  
        # data handling and plotting
        "tidyverse",
        "ragg",
        "writexl",
        "knitr",
        "janitor",
        "scales",
        "ggsci",
        "patchwork",
        "UpSetR",
        "ComplexUpset",
        # time series analysis
        #"lme4",
        #"performance",
        #"mgcv",
        #"MuMIn",
        #"broom.mixed",
        #"gt",
        #"fable",
        # association matrix analysis
        "FactoMineR",
        "factoextra"
        ),
        repos="http://nexus.tde.imperial.nhs.uk:8081/repository/cran/",
        lib="/home/azureuser/R"
        )

# setting default library path
.libPaths("/home/azureuser/R")

# data handling and plotting
library(tidyverse)
library(ragg)
library(writexl)
library(knitr)
library(janitor)
library(scales)
library(ggsci)
library(patchwork)
library(UpSetR)
library(ComplexUpset)

# time series analysis
#library(lme4)
#library(performance)
#library(mgcv)
#library(MuMIn)
#library(broom.mixed)
#library(gt)
#library(fable)

# association matrix analysis
library(FactoMineR)
library(factoextra)

lean load¶

In [ ]:
# removing everything other than base R
#pks <- setdiff(installed.packages()[, "Package"], rownames(installed.packages(priority = "base")))

#remove.packages(pks)

# installing only tidyverse
install.packages(
    c("tidyverse",
       "ggsci",
       "knitr"
       #"ComplexUpset",
       #"UpSetR"
       ),
repos="http://nexus.tde.imperial.nhs.uk:8081/repository/cran/",
        lib="/home/azureuser/R"
        )

library(tidyverse)
library(ggsci)
library(knitr)
#library(ComplexUpset)
#library(UpSetR)

checking packages¶

In [ ]:
# list all packages
#installed.packages()[,"Package"]

# find specific packages
"package::FactoMineR" %in% search()

adding late-install packages¶

make sure to include above for next time¶

In [ ]:
install.packages(
        #"ComplexUpset",
        #"FactoMineR",
        "factoextra",
        repos="http://nexus.tde.imperial.nhs.uk:8081/repository/cran/",
        dependencies=TRUE,
        lib="/home/azureuser/R"
        )

# setting default library path
.libPaths("/home/azureuser/R") 

#library(ComplexUpset)
#library(FactoMineR)
library(factoextra)

checking package versions¶

In [ ]:
pkgs <- installed.packages()[, c("Package", "Version")]

pkgs <- as.data.frame(pkgs, stringsAsFactors = F)

pkgs$Citation <- vapply(
    pkgs$Package,
    function(pkg) {
        tryCatch(
            {
            cit <- citation(pkg)
            paste(format(cit, style = "text")[1], collapse = " ")
            },
            error = function(e) "No Citation Found"
        )

    },
    character(1)
)

pkgs

individual packages¶

In [ ]:
packageVersion("stats")

uploading data¶

In [ ]:
# microbiology data
micro <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/microbiology_pull_final_08042025.csv")
# demographics data
demographics <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/demographics_pull_final_10032025.csv")
# episodes data
episodes <-  read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/episodes_pull_final_10032025.csv")

data are slow to upload so creating checkpoint data to carry forward¶

three different "buttons" easiest to use when fixing errors that may occur below¶

In [ ]:
micro_cf <- micro
In [ ]:
demographics_cf <- demographics
In [ ]:
episodes_cf <- episodes

reclassifying date columns¶

microbiology data¶

In [ ]:
micro_cf<-micro_cf |>
  mutate(SAMPLE_COLLECTED_DT = lubridate::as_date(ymd_hms(SAMPLE_COLLECTED_DT)))
class(micro_cf$SAMPLE_COLLECTED_DT)

episodes data¶

In [ ]:
episodes_cf<-episodes_cf |>
  mutate(across(c(ADMISSION_DATE, EPISODE_START_DATE, EPISODE_END_DATE, DISCHARGE_DATE), ymd))
class(episodes_cf$ADMISSION_DATE)

cleaning demographics data¶

In [ ]:
print("before:")
levels(as.factor(demographics_cf$ETHNICITY_DESC))

demographics_cf <-
demographics_cf |>
  mutate(ETHNICITY_DESC = fct_collapse(ETHNICITY_DESC,
    Asian = c("asian or asian british - bangladeshi",
              "asian or asian british - indian",
              "asian or asian british - pakistani",
              "asian - any other asian background",
              "chinese",
              "other - chinese"),
    White = c("white - british",
              "white - irish",
              "white - any other white background"),
    Black = c("black or black british - african",
              "african (except somali)",
              "black or black british - caribbean",
              "black - any other black background"),
    Mixed = c("mixed - white and asian",
              "white and asian",
              "mixed - white and black african",
              "mixed - white and black caribbean",
              "mixed - any other mixed background"),
    Other = c("other - any other ethnic group",
              "any other ethnic group",
              "not known",
              "not stated",
              "british",
              "other - not stated",
              "other - not known")
  ))

print("after:")
levels(as.factor(demographics_cf$ETHNICITY_DESC))

cleaning microbiology data¶

defining all susceptibility testing data and blood cultures only susceptibility testing data¶

In [ ]:
# all microbiology susceptibility testing data
micro_cf_ALL <-
micro_cf |>
    # removing colums where sensitivity is NA or does not contain ":"
    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, ":")) |>
    # filtering for susceptiblity testing data
    filter(str_detect(ORDER_NAME, "susceptibility"))

# creating intermediate data frame for left_join
df <-
micro_cf |>
    # filtering for blood cultures only
    filter(str_detect(ORDER_NAME, "blood"))

# blood cultures only susceptibility testing data
micro_cf_BLOOD <-
micro_cf_ALL |>
    left_join(df |>
                # selecting only columns of interest
                select(SUBJECT,
                       SAMPLE_COLLECTED_DT,
                       CULTURE_TYPE=ORDER_NAME),
                by = c("SUBJECT",
                       "SAMPLE_COLLECTED_DT"),
                relationship = "many-to-many") |>
    # moving new column before bugs column
    relocate(CULTURE_TYPE,.before = "ORGANISM_BUG") |>
    filter(!is.na(CULTURE_TYPE)) |>
    distinct()

checking data¶

In [ ]:
print("All microbiology susceptibility testing data:")
head(micro_cf_ALL)
print("Number of records in all microbiology susceptibility testing data:")
length(micro_cf_ALL$SUBJECT)
print("Number of distinct patients in all microbiology susceptibility testing  data:")
n_distinct(micro_cf_ALL$SUBJECT)

print("Blood cultures only susceptibility testing data:")
head(micro_cf_BLOOD)
print("Number of records in blood cultures only susceptibility testing data:")
length(micro_cf_BLOOD$SUBJECT)
print("Number of distinct patients in blood cultures only susceptibility testing data:")
n_distinct(micro_cf_BLOOD$SUBJECT)

defining bugs and basic column fixes¶

all microbiology susceptibility testing data¶

In [ ]:
micro_cf_ALL <-
micro_cf_ALL |>
    # removing colums where sensitivity is NA or does not contain ":"
    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, ":")) |>
    # focussing only on susceptiblity testing data
    filter(str_detect(ORDER_NAME, "susceptibility")) |>
    # copying original bugs column
    mutate(OLD_BUGS=ORGANISM_BUG) |>
    # removing special symbols in bugs column and creating new column
    mutate(ORGANISM_OR_BUG = str_replace_all(OLD_BUGS, "[^[:alnum:] ]", "")
    ) |>
    # identifying bugs
    mutate(
    ORGANISM_OR_BUG = case_when(
      # Klebsiella pneumoniae
      str_detect(ORGANISM_OR_BUG, "klebsiella pneumoniae") ~ "Klebsiella pneumoniae",
      # Klebsiella species
      str_detect(ORGANISM_OR_BUG, "klebsiella") & ORGANISM_OR_BUG != "Klebsiella pneumoniae" ~ "Klebsiella spp.",
      # E. coli
      str_detect(ORGANISM_OR_BUG, regex("escherichia coli|e.coli", ignore_case = TRUE)) ~ "Escherichia coli",
      # Citrobacter species
      str_detect(ORGANISM_OR_BUG, "citrobacter") ~ "Citrobacter spp.",
      # Enterobacter species
      str_detect(ORGANISM_OR_BUG, "enterobacter") ~ "Enterobacter spp.",
      # Proteus species
      str_detect(ORGANISM_OR_BUG, "proteus") ~ "Proteus spp.",
      # Serratia species
      str_detect(ORGANISM_OR_BUG, "serratia") ~ "Serratia spp.",
      # other species (e.g., Gram positives)
      TRUE ~ "Other, including Gram +ves"
    )) |>
    # relevelling factor
    mutate(
    ORGANISM_OR_BUG=factor(ORGANISM_OR_BUG,
      levels = c("Escherichia coli",
                  "Klebsiella pneumoniae",
                  "Citrobacter spp.",
                  "Enterobacter spp.",
                  "Hafnia alvei",
                  "Klebsiella spp.",
                  "Morganella morganii",
                  "Proteus spp.",
                  "Serratia spp.",
                  "Other, including Gram +ves"
    ))) |>
    # splitting sensitivity column into 2 columns
    separate(SENSITIVITY, into = c("DRUG", "SUSCEPTIBILITY"), sep = " : ") |>
    # capitalising drugs and susceptibility values
    mutate(DRUG = str_to_title(DRUG),
           SUSCEPTIBILITY = str_to_title(SUSCEPTIBILITY)) |>
    select(SUBJECT,
           SAMPLE_COLLECTED_DT,
           OLD_BUGS,
           ORGANISM_OR_BUG,
           DRUG,
           SUSCEPTIBILITY) |>
    # filtering where no valid drug sensitivity
    filter(!is.na(SUSCEPTIBILITY))

blood cultures only susceptibility testing data¶

In [ ]:
micro_cf_BLOOD <-
micro_cf_BLOOD |>
    # removing colums where sensitivity is NA or does not contain ":"
    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, ":")) |>
    # focussing only on susceptiblity testing data
    filter(str_detect(ORDER_NAME, "susceptibility")) |>
    # copying original bugs column
    mutate(OLD_BUGS=ORGANISM_BUG) |>
    # removing special symbols in bugs column and creating new column
    mutate(ORGANISM_OR_BUG = str_replace_all(OLD_BUGS, "[^[:alnum:] ]", "")
    ) |>
    # identifying bugs
    mutate(
    ORGANISM_OR_BUG = case_when(
      # Klebsiella pneumoniae
      str_detect(ORGANISM_OR_BUG, "klebsiella pneumoniae") ~ "Klebsiella pneumoniae",
      # Klebsiella species
      str_detect(ORGANISM_OR_BUG, "klebsiella") & ORGANISM_OR_BUG != "Klebsiella pneumoniae" ~ "Klebsiella spp.",
      # E. coli
      str_detect(ORGANISM_OR_BUG, regex("escherichia coli|e.coli", ignore_case = TRUE)) ~ "Escherichia coli",
      # Citrobacter species
      str_detect(ORGANISM_OR_BUG, "citrobacter") ~ "Citrobacter spp.",
      # Enterobacter species
      str_detect(ORGANISM_OR_BUG, "enterobacter") ~ "Enterobacter spp.",
      # Proteus species
      str_detect(ORGANISM_OR_BUG, "proteus") ~ "Proteus spp.",
      # Serratia species
      str_detect(ORGANISM_OR_BUG, "serratia") ~ "Serratia spp.",
      # other species (e.g., Gram positives)
      TRUE ~ "Other, including Gram +ves"
    )) |>
    # relevelling factor
    mutate(
    ORGANISM_OR_BUG=factor(ORGANISM_OR_BUG,
      levels = c("Escherichia coli",
                  "Klebsiella pneumoniae",
                  "Citrobacter spp.",
                  "Enterobacter spp.",
                  "Hafnia alvei",
                  "Klebsiella spp.",
                  "Morganella morganii",
                  "Proteus spp.",
                  "Serratia spp.",
                  "Other, including Gram +ves"
    ))) |>
    # splitting sensitivity column into 2 columns
    separate(SENSITIVITY, into = c("DRUG", "SUSCEPTIBILITY"), sep = " : ") |>
    # capitalising drugs and susceptibility values
    mutate(DRUG = str_to_title(DRUG),
           SUSCEPTIBILITY = str_to_title(SUSCEPTIBILITY)) |>
    select(SUBJECT,
           SAMPLE_COLLECTED_DT,
           CULTURE_TYPE,
           OLD_BUGS,
           ORGANISM_OR_BUG,
           DRUG,
           SUSCEPTIBILITY) |>
    # filtering where no valid drug sensitivity
    filter(!is.na(SUSCEPTIBILITY))

dealing with breakpoint values¶

which drugs have breakpoint values that need to be decoded?¶

In [ ]:
drugs_to_decode <-
#micro_cf_ALL |>
micro_cf_BLOOD |>
# filtering out actual written values for susceptibility
filter(str_count(SUSCEPTIBILITY, "[A-Za-z]") < 2) |>
    select(DRUG) |>
    distinct() |>
    arrange(DRUG)

kable(drugs_to_decode)

loading breakpoints data¶

In [ ]:
# microbiology data
mic_breakpoints <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/AB_guidelines.csv")
head(mic_breakpoints)

tidying susceptibility column¶

all microbiology susceptibility testing data¶

In [ ]:
print("before:")
levels(as.factor(micro_cf_ALL$SUSCEPTIBILITY))

micro_cf_ALL <-
micro_cf_ALL |> 
    mutate(SUSCEPTIBILITY = case_when(
        # values to change
        SUSCEPTIBILITY == "Highly Resistant" ~ "Resistant",
        SUSCEPTIBILITY %in% c("Susceptible With Optimised Dosing, Refer To Antimicrobial Policy","Sensitive") ~ "Susceptible",
        SUSCEPTIBILITY == "Not Determined." ~ "Not Determined",
        TRUE ~ SUSCEPTIBILITY
    )) |>
    # !!! addressing MIC breakpoint values !!!
    # remove special symbols, "=", ">", and "<"
    mutate(SUSCEPTIBILITY = str_remove_all(SUSCEPTIBILITY,"[=><]")) |>
    mutate(DRUG = toupper(DRUG)) |>
    # left joining with breakpoints data
    left_join(mic_breakpoints |>
                # selecting columns of interest
                select(DRUG,S,R),
            by = "DRUG"
            ) |>
    # decoding MIC values
    mutate(DECODED = case_when(
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) >= R ~ "Resistant",
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) <= S ~ "Susceptible",
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) > S & as.numeric(SUSCEPTIBILITY) < R ~ "Intermediate",
    TRUE ~ as.character(SUSCEPTIBILITY)
    )) |>
    # checking decoding logic
    #filter(str_detect(SUSCEPTIBILITY,"\\d")) |>
    # filtering "bad" values, not captured by scalable logic
    filter(DECODED %in% c("Resistant","Intermediate","Susceptible","Not Determined"))

print("after:")
levels(as.factor(micro_cf_ALL$DECODED))

blood cultures only susceptibility testing data¶

In [ ]:
print("before:")
levels(as.factor(micro_cf_BLOOD$SUSCEPTIBILITY))

micro_cf_BLOOD <-
micro_cf_BLOOD |> 
    mutate(SUSCEPTIBILITY = case_when(
        # values to change
        SUSCEPTIBILITY == "Highly Resistant" ~ "Resistant",
        SUSCEPTIBILITY %in% c("Susceptible With Optimised Dosing, Refer To Antimicrobial Policy","Sensitive") ~ "Susceptible",
        SUSCEPTIBILITY == "Not Determined." ~ "Not Determined",
        TRUE ~ SUSCEPTIBILITY
    )) |>
    # !!! addressing MIC breakpoint values !!!
    # remove special symbols, "=", ">", and "<"
    mutate(SUSCEPTIBILITY = str_remove_all(SUSCEPTIBILITY,"[=><]")) |>
    mutate(DRUG = toupper(DRUG)) |>
    # left joining with breakpoints data
    left_join(mic_breakpoints |>
                # selecting columns of interest
                select(DRUG,S,R),
            by = "DRUG"
            ) |>
    # decoding MIC values
    mutate(DECODED = case_when(
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) >= R ~ "Resistant",
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) <= S ~ "Susceptible",
        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) > S & as.numeric(SUSCEPTIBILITY) < R ~ "Intermediate",
    TRUE ~ as.character(SUSCEPTIBILITY)
    )) |>
    # checking decoding logic
    #filter(str_detect(SUSCEPTIBILITY,"\\d")) |>
    # filtering "bad" values, not captured by scalable logic
    filter(DECODED %in% c("Resistant","Intermediate","Susceptible","Not Determined"))

print("after:")
levels(as.factor(micro_cf_BLOOD$DECODED))

defining drug classes¶

all microbiology susceptibility testing data¶

In [ ]:
micro_cf_ALL <-
micro_cf_ALL  |>
    # collapsing tazocin (brand name) and pip-taz (chemical name) into one
    mutate(DRUG = case_when(
        DRUG %in% c("PIPERACILLIN-TAZOBACTAM","TAZOCIN") ~ "TAZOCIN",
        TRUE ~ DRUG
    )) |>
    # only defining classes for drugs of interest
    mutate(DRUG_CLASS = case_when(
        # aminoglycosides
        DRUG %in% c("AMIKACIN", "GENTAMICIN", "TOBRAMYCIN","NEOMYCIN","SPECTINOMYCIN","STREPTOMYCIN","KANAMYCIN") ~ "Aminoglycosides",
        # carbapenems
        DRUG %in% c("ERTAPENEM","IMIPENEM","MEROPENEM") ~ "Carbapenems",
        # cephalosporins
        DRUG %in% c("CEFEPIME", "CEFIDEROCOL", "CEFIXIME", "CEFOTAXIME", "CEFOXITIN", "CEFPODOXIME", "CEFTAZIDIME", "CEFTAZIDIME-AVIBACTAM", "CEFTAROLINE", "CEFTOLOZANE-TAZOBACTAM","CEFTRIAXONE","CEFUROXIME","CEPHALEXIN") ~ "Cephalosporins",
        # fluoroquinolones
        DRUG %in% c("CIPROFLOXACIN","LEVOFLOXACIN","NORFLOXACIN", "OFLOXACIN","MOXIFLOXACIN","PEFLOXACIN","QUINOLONE","NALIDIXIC ACID") ~ "Fluoroquinolones",
        # monobactams
        DRUG %in% c("AZTREONAM") ~ "Monobactams",
        # penicillins
        DRUG %in% c("AMOXYCILLIN","AUGMENTIN","CO-AMOXICLAV","TICARCILLIN-CLAVULANATE","FLUCLOXACILLIN","TAZOCIN","TEMOCILLIN","PENICILLIN") ~ "Penicillins",
        #macrolides
        DRUG %in% c("AZITHROMYCIN","CLARITHROMYCIN","ERYTHROMYCIN") ~ "Macrolides",
        # sulfonamides
        DRUG %in% c("COTRIMOXAZOLE") ~ "Sulfonamides",
        # other
        TRUE ~ "Other",
    ))

blood cultures only susceptibility testing data¶

In [ ]:
micro_cf_BLOOD <-
micro_cf_BLOOD |>
    # collapsing tazocin (brand name) and pip-taz (chemical name) into one
    mutate(DRUG = case_when(
        DRUG %in% c("PIPERACILLIN-TAZOBACTAM","TAZOCIN") ~ "TAZOCIN",
        TRUE ~ DRUG
    )) |>
    # only defining classes for drugs of interest
    mutate(DRUG_CLASS = case_when(
        # aminoglycosides
        DRUG %in% c("AMIKACIN", "GENTAMICIN", "TOBRAMYCIN","NEOMYCIN","SPECTINOMYCIN","STREPTOMYCIN","KANAMYCIN") ~ "Aminoglycosides",
        # carbapenems
        DRUG %in% c("ERTAPENEM","IMIPENEM","MEROPENEM") ~ "Carbapenems",
        # cephalosporins
        DRUG %in% c("CEFEPIME", "CEFIDEROCOL", "CEFIXIME", "CEFOTAXIME", "CEFOXITIN", "CEFPODOXIME", "CEFTAZIDIME", "CEFTAZIDIME-AVIBACTAM", "CEFTAROLINE", "CEFTOLOZANE-TAZOBACTAM","CEFTRIAXONE","CEFUROXIME","CEPHALEXIN") ~ "Cephalosporins",
        # fluoroquinolones
        DRUG %in% c("CIPROFLOXACIN","LEVOFLOXACIN","NORFLOXACIN", "OFLOXACIN","MOXIFLOXACIN","PEFLOXACIN","QUINOLONE","NALIDIXIC ACID") ~ "Fluoroquinolones",
        # monobactams
        DRUG %in% c("AZTREONAM") ~ "Monobactams",
        # penicillins
        DRUG %in% c("AMOXYCILLIN","AUGMENTIN","CO-AMOXICLAV","PIPERACILLIN-TAZOBACTAM","TICARCILLIN-CLAVULANATE","FLUCLOXACILLIN","TAZOCIN","TEMOCILLIN","PENICILLIN") ~ "Penicillins",
        #macrolides
        DRUG %in% c("AZITHROMYCIN","CLARITHROMYCIN","ERYTHROMYCIN") ~ "Macrolides",
        # sulfonamides
        DRUG %in% c("COTRIMOXAZOLE") ~ "Sulfonamides",
        # other
        TRUE ~ "Other",
    ))

joining demographics data, episodes data, & microbiology data¶

creating all_data (can take ~5 mins to run)¶

1. joining demographics data & episodes data¶

2. performing join with all microbiology susceptibility testing data and filtering where the following conditions are met:¶

SAMPLE_COLLECTED_DT >= ADMISSION_DATE & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE¶

In [ ]:
all_data <- 
episodes_cf |>
    # performing join
    left_join(demographics_cf,
        by = "SUBJECT") |>
    # replacing NA values resulting from join
    mutate(across(c(BIRTH_DATE:GENDER_DESC), ~replace_na(.x, "No Data"))) |>
    # relocating demographics columns
    relocate(colnames(demographics_cf), .before = "SPELL_IDENTIFIER") |>
    # performing left join with micro data
    left_join(micro_cf_ALL,
        by = "SUBJECT",
        relationship = "many-to-many") |>
    # marking difference where the following conditions are met:
        # 1. SAMPLE_COLLECTED_DT >= ADMISSION_DATE
        # 2. SAMPLE_COLLECTED_DT <= DISCHARGE_DATE
    mutate(WITHIN_SPELL = if_else(
            SAMPLE_COLLECTED_DT >= ADMISSION_DATE &
            SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, TRUE, FALSE)) |>
    # removing unwanted episodes data
    filter(WITHIN_SPELL == TRUE)

head(all_data)

checking joins makes sense¶

In [ ]:
print("The number of rows in the episodes data:")
length(episodes_cf$SUBJECT)
print("The number of distinct patients for which we have episodes data (1 patient can have more than 1 spell or episode):")
n_distinct(episodes_cf$SUBJECT)

print("The number of rows in the microbiology susceptibiltiy testing data:")
length(micro_cf_ALL$SUBJECT)
print("The number of distinct patients for which we have microbiology susceptibiltiy testing data (1 patient can have many cultures taken from many different spells or episodes):")
n_distinct(micro_cf_ALL$SUBJECT)

print("The number of rows in the joined data:")
length(all_data$SUBJECT)
print("The number of distinct patients for which we have matching episodes data and microbiology. That is, the patient was sampled whilst admitted to hospital:")
n_distinct(all_data$SUBJECT)

final tidying steps¶

In [ ]:
all_data <-
all_data |>
    # identifying which isolates were collected 48hrs after admission
    mutate(AFTER_48HRS = if_else(SAMPLE_COLLECTED_DT > (ADMISSION_DATE + 2) & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, "Collection after 48 hours of admission", "Collection within 48 hours of admission")) |>
    # reodering levels
    mutate(AFTER_48HRS = fct_relevel(AFTER_48HRS, "Collection after 48 hours of admission", "Collection within 48 hours of admission")) |>
    # defining cut-off date for discharge date - so no patients still in hospital are included
    filter(DISCHARGE_DATE <= ymd("2025-01-01"))

head(all_data)

creating bld_data¶

1. joining demographics data & episodes data¶

2. performing join with blood culture only susceptibility testing data and filtering where the following conditions are met:¶

SAMPLE_COLLECTED_DT >= ADMISSION_DATE & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE¶

In [ ]:
bld_data <- 
episodes_cf |>
    # performing join
    left_join(demographics_cf,
        by = "SUBJECT") |>
    # replacing NA values resulting from join
    mutate(across(c(BIRTH_DATE:GENDER_DESC), ~replace_na(.x, "No Data"))) |>
    # relocating demographics columns
    relocate(colnames(demographics_cf), .before = "SPELL_IDENTIFIER") |>
    # performing left join with blood cultures only data
    left_join(micro_cf_BLOOD,
        by = "SUBJECT",
        relationship = "many-to-many") |>
    # marking difference where the following conditions are met:
        # 1. SAMPLE_COLLECTED_DT >= ADMISSION_DATE
        # 2. SAMPLE_COLLECTED_DT <= DISCHARGE_DATE
    mutate(WITHIN_SPELL = if_else(
            SAMPLE_COLLECTED_DT >= ADMISSION_DATE &
            SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, TRUE, FALSE)) |>
    # removing unwanted episodes data
    filter(WITHIN_SPELL == TRUE)

head(bld_data)

checking joings make sense¶

In [ ]:
print("The number of rows in the episodes data:")
length(episodes_cf$SUBJECT)
print("The number of distinct patients for which we have episodes data (1 patient can have more than 1 spell or episode):")
n_distinct(episodes_cf$SUBJECT)

print("The number of rows in the blood cultures only susceptibiltiy testing data:")
length(micro_cf_BLOOD$SUBJECT)
print("The number of distinct patients for which we have blood cultures only susceptibiltiy testing data (1 patient can have many cultures taken from many different spells or episodes):")
n_distinct(micro_cf_BLOOD$SUBJECT)

print("The number of rows in the joined data:")
length(bld_data$SUBJECT)
print("The number of distinct patients for which we have matching episodes data and  blood cultures only susceptibiltiy testing data. That is, the patient was sampled whilst admitted to hospital:")
n_distinct(bld_data$SUBJECT)

final tidying steps¶

<<< 2. LOADING WORKSPACE >>>¶

In [ ]:
bld_data <-
bld_data |>
    # identifying which isolates were collected 48hrs after admission
    mutate(AFTER_48HRS = if_else(SAMPLE_COLLECTED_DT > (ADMISSION_DATE + 2) & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, "Collection after 48 hours of admission", "Collection within 48 hours of admission")) |>
    # reodering levels
    mutate(AFTER_48HRS = fct_relevel(AFTER_48HRS, "Collection after 48 hours of admission", "Collection within 48 hours of admission")) |>
    # defining cut-off date for discharge date - so no patients still in hospital are included
    filter(DISCHARGE_DATE <= ymd("2025-01-01"))

head(bld_data)
In [ ]:
load("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/09052025.RData")

saving workspace¶

last saved: 29042025¶

In [ ]:
ls()
## BE CAREFUL NOT TO RUN THE BELOW WHEN INAPPROPRIATE
#save.image("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/X.RData")

checking numbers for thesis¶

In [ ]:
n_distinct(micro_cf_ALL)
n_distinct(micro_cf_ALL$SUBJECT)
n_distinct(micro_cf_BLOOD)
n_distinct(micro_cf_BLOOD$SUBJECT)
n_distinct(all_data$SUBJECT)
n_distinct(bld_data$SUBJECT)

<<< 3. PLOTTING >>>¶

exact plotting dimensions to be determined before final export, but all plots ready to be considered for final export in "/checked&ready/" directory¶

micro_cf_ALL : all microbiology susceptibility testing data¶

micro_cf_BLOOD : microbiology susceptibility testing data attributed to blood cultures only¶

all_data : all microbiology susceptibility testing data joined with available & matching episodes/demographics data¶

bld_data : microbiology susceptibility testing data attributed to blood cultures only joined with available & matching episodes/demographics data¶

identifying end date cut off that make sense for plotting¶

In [ ]:
micro_cf_ALL |>
# filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG) |>
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(MONTH < "2025-04-01") |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    MONTH
  ) |>
  tally() |>
  arrange(n)

filter(MONTH < "2025-04-01") works well as months before April 2025 represent complete collection months¶

In [ ]:
end_date <- as.Date("2025-04-01")

bug counts and proportions: microbiology data¶

1. line chart CHECKED & READY¶

In [ ]:
# line chart
#micro_cf_ALL |>
micro_cf_BLOOD |>
# filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG) |>
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    MONTH
  ) |>
  tally() |>
ggplot(aes(x=MONTH,
           y=n,
           colour=ORGANISM_OR_BUG)) +
  geom_line(alpha=0.8) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  labs(x = "Date",
       y = "Isolate Count",
       colour = "Organism") +
  theme_bw() +
  scale_colour_manual(values = c("#008080",
                                 "#FFA500",                               
                                 "#ea705d",
                                 "#71c9dd",
                                 "#33b29f",
                                 "#6376a0",
                                 "#f5af98",
                                 "#9da6c3",
                                 "#a6dace")) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11,face = "italic"), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11))

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/1_micro_cf_ALL_bug_counts_line_chart_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/1_micro_cf_BLOOD_bug_counts_line_chart_GTG.jpeg",
       #height= 5,
       #width=10)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_ALL_bug_counts.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_BLOOD_bug_counts.jpeg",
       width=8,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

2. proportions chart CHECKED & READY¶

In [ ]:
# proportions chart
#micro_cf_ALL |>
micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG) |>
  distinct() |>
  # creating month column
  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(month < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    month
  ) |>
  summarise(total = n()) |>
  ungroup() |>
  group_by(month) |>
  mutate(prop = total / sum(total)) |>
  ggplot(aes(x=month,
             y=prop,
             fill=ORGANISM_OR_BUG)) +
  geom_bar(stat="identity",alpha=0.8) +
  scale_y_continuous(labels = function(x){paste0(x*100,"%")}) +
  theme_bw() +
  labs(x = "Date",
       y = "Proportion (%)",
       fill = "Organism") +
  theme_bw() +
  scale_fill_manual(values = c("#008080",
                               "#FFA500",                               
                               "#ea705d",
                               "#71c9dd",
                               "#33b29f",
                               "#6376a0",
                               "#f5af98",
                               "#9da6c3",
                               "#a6dace")) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11,face = "italic"), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/2_micro_cf_ALL_bug_proportions_line_chart_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/2_micro_cf_BLOOD_bug_proportions_line_chart_GTG.jpeg",
       #height= 5,
       #width=10)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_ALL_bug_proportions.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_BLOOD_bug_proportions.jpeg",
       width=8,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting bug counts and proportions: all_data, bld_data¶

3. line chart CHECKED & READY¶

In [ ]:
# line chart
all_data |>
#bld_data |>
# filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG) |>
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    MONTH
  ) |>
  tally() |>
ggplot(aes(x=MONTH,
           y=n,
           colour=ORGANISM_OR_BUG)) +
  geom_line(alpha=0.8) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  labs(x = "Date",
       y = "Count",
       colour = "Organism") +
  theme_bw() +
  scale_colour_manual(values = c("#008080",
                                 "#FFA500",                               
                                 "#ea705d",
                                 "#71c9dd",
                                 "#33b29f",
                                 "#6376a0",
                                 "#f5af98",
                                 "#9da6c3",
                                 "#a6dace")) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11,face = "italic"), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11))

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/3_all_data_bug_counts_line_chart_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/3_bld_data_bug_counts_line_chart_GTG.jpeg",
       height= 5,
       width=10)

4. proportions chart CHECKED & READY¶

In [ ]:
# proportions chart
all_data |>
#bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG) |>
  distinct() |>
  # creating month column
  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(month < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    month
  ) |>
  summarise(total = n()) |>
  ungroup() |>
  group_by(month) |>
  mutate(prop = total / sum(total)) |>
  ggplot(aes(x=month,
             y=prop,
             fill=ORGANISM_OR_BUG)) +
  geom_bar(stat="identity",alpha=0.8) +
  scale_y_continuous(labels = percent) +
  theme_bw() +
  labs(x = "Date",
       y = "Proportion (%)",
       fill = "Organism") +
  theme_bw() +
  scale_fill_manual(values = c("#008080",
                               "#FFA500",                               
                               "#ea705d",
                               "#71c9dd",
                               "#33b29f",
                               "#6376a0",
                               "#f5af98",
                               "#9da6c3",
                               "#a6dace")) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11,face = "italic"), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8)

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/4_all_data_bug_counts_proportions_chart_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/4_bld_data_bug_counts_proportions_chart_GTG.jpeg",
       height= 5,
       width=10)

plotting HO infections vs CO infections counts and proportions for K. pneumoniae and E. coli: all_data, bld_data¶

5. line chart CHECKED & READY¶

In [ ]:
# line chart
#all_data |>
bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    HO,
    MONTH
  ) |>
  tally() |>
  #View()
  # plotting data
  ggplot(aes(x=MONTH,
             y=n,
             colour=HO)) +
  geom_line(alpha=0.8) +
  # sizing
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  theme_bw() +
  scale_colour_npg() +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        strip.text = element_text(size=12,
                                  face = "italic"), 
        strip.background = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  facet_wrap(~ORGANISM_OR_BUG) +
  labs(x = "Date",
       y = "Isolate Count",
       colour="Infection Category")

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/5_all_data_HO_vs_CO_line_chart_29052025.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/5_bld_data_HO_vs_CO_line_chart_29052025.jpeg",
       #height= 3,
       #width=8)

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_all_data_bug_counts.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_bld_data_bug_counts.jpeg",
       width=16,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

6. proportions chart CHECKED & READY¶

In [ ]:
# proportions chart
#all_data |>
bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset","Undefined"))) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(HO,
           ORGANISM_OR_BUG,
           MONTH) |>
  summarise(total = n()) |>
  ungroup() |>
  group_by(MONTH,ORGANISM_OR_BUG) |>
  mutate(prop = total / sum(total)) |>
  #View()
  # plotting data
  ggplot(aes(x=MONTH,
             y=prop,
             fill=HO)) +
  geom_bar(stat="identity",alpha=0.8) +
  scale_y_continuous(labels = function(x){paste0(x*100,"%")}) +
  theme_bw() +
  labs(x = "Date",
       y = "Proportion (%)",
       fill = "Infection Category") +
  scale_fill_npg() +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        strip.text = element_text(size=12,face = "italic"), 
        strip.background = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  facet_wrap(~ORGANISM_OR_BUG)  +
  # sizing
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/6_all_data_HO_vs_CO_proportions_chart_29052025.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/6_bld_data_HO_vs_CO_proportions_chart_29052025.jpeg",
       #height= 3,
       #width=16)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_all_data_bug_proportions.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_bld_data_bug_proportions.jpeg",
       width=16,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting HO infections vs CO infections counts and proportions for all bugs: all_data, bld_data (minus non-Enterobacteriaceae)¶

7. line chart CHECKED & READY¶

In [ ]:
# line chart
#all_data |>
bld_data |>
 # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
   # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    HO,
    MONTH
  ) |>
  tally() |>
   # plotting data
  ggplot(aes(x=MONTH,
             y=n,
             colour=HO)) +
  geom_line(alpha=0.8) +
  # sizing
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  theme_bw() +
  scale_colour_npg() +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        strip.text = element_text(size=12,face = "italic"), 
        strip.background = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  labs(x = "Date",
       y = "Isolate Count",
       colour="Infection Category") +
  facet_wrap(~ORGANISM_OR_BUG)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/7_all_data_HO_vs_CO_line_chart_v2_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/7_bld_data_HO_vs_CO_line_chart_v2_GTG.jpeg",
       #height= 9,
       #width=16)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_all_data_bug_counts_alternate.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_bld_data_bug_counts_alternate.jpeg",
       width=16,
       height=9,
       units="in",
       res=300
)
print(last_plot())
dev.off()

8. proportions chart CHECKED & READY¶

In [ ]:
# proportions chart
#all_data |>
bld_data |>
# filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset","Undefined"))) |>
   # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(HO,
           ORGANISM_OR_BUG,
           MONTH) |>
  summarise(total = n()) |>
  ungroup() |>
  group_by(MONTH,ORGANISM_OR_BUG) |>
  mutate(prop = total / sum(total)) |>
  #View()
  # plotting data
  ggplot(aes(x=MONTH,
             y=prop,
             fill=HO)) +
  geom_bar(stat="identity",alpha=0.8) +
  scale_y_continuous(labels = function(x){paste0(x*100,"%")}) +
  theme_bw() +
  labs(x = "Date",
       y = "Proportion (%)",
       fill = "Infection Category") +
  scale_fill_npg() +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        strip.text = element_text(size=12,face = "italic"), 
        strip.background = element_blank(),
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  facet_wrap(~ORGANISM_OR_BUG) +
  # sizing
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/8_all_data_HO_vs_CO_proportions_chart_v2_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/8_bld_data_HO_vs_CO_proportions_chart_v2_GTG.jpeg",
       #height= 9,
       #width=16)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_all_data_bug_proportions_alternate.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_bld_data_bug_proportions_alternate.jpeg",
       width=16,
       height=9,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting bug proportions across HO vs CO infections: all_data, bld_data¶

9. proportions chart¶

In [ ]:
# proportions chart
#all_data |>
bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         WITHIN_SPELL,
         AFTER_48HRS) |>
  distinct() |>
  group_by(ORGANISM_OR_BUG,
           AFTER_48HRS) |>
  filter(n()>5) |>
  ungroup() |>
  # creating month column
  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset","Undefined"))) |>
  # filtering incomplete end month
  filter(month < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    HO,
    month
  ) |>
  summarise(total = n()) |>
  ungroup() |>
  group_by(HO,month) |>
  mutate(prop = total / sum(total)) |>
  ggplot(aes(x=month,
             y=prop,
             fill=ORGANISM_OR_BUG)) +
  geom_bar(stat="identity",alpha=0.8) +
  scale_y_continuous(labels = function(x){paste0(x*100,"%")}) +
  theme_bw() +
  labs(x = "Date",
       y = "Proportion (%)",
       fill = "Organism") +
  theme_bw() +
  scale_fill_manual(values = c("#008080",
                               "#FFA500",                               
                               "#ea705d",
                               "#71c9dd",
                               "#33b29f",
                               "#6376a0",
                               "#f5af98",
                               "#9da6c3",
                               "#a6dace")) +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        strip.text = element_text(size=12), 
        strip.background = element_blank(),
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11,face = "italic"), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11)) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  facet_wrap(~HO)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/9_all_data_HO_vs_CO_proportions_chart_v3_GTG.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/9_bld_data_HO_vs_CO_proportions_chart_v3_GTG.jpeg",
       #height= 3,
       #width=10.6)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/5_all_data_bug_proportions_alternate2.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/5_bld_data_bug_proportions_alternate2.jpeg",
       width=10.6,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting E. coli and K. pneumoniae monthly resistance rates selected drugs¶

10a. line chart: all microbiology susceptibility testing data (micro_cf_All & micro_cf_BLOOD)¶

In [ ]:
# defining breaks for marker sizes
breaks<-c(5,10,20,50,100,200,400,800,Inf)
#reordering drugs panels to match x axis order of first resistance plot
drugs_order <- c("Amikacin", "Gentamicin", "Ertapenem", "Meropenem", "Ceftazidime", "Ceftriaxone","Ciprofloxacin","Amoxycillin","Co-Amoxiclav","Tazocin","Temocillin","Cotrimoxazole")

# line chart
micro_cf_ALL |>
#micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # selecting columns of interest
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         DRUG,
         DRUG_CLASS,
         DECODED) |>
  # creating time column
  mutate(
       time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")
       #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "quarter")
       ) |>
  # filtering incomplete end time
  filter(time < end_date) |>
  # counting total bugs-drug combinations per time
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG) |>
  # creating total timely count column
  mutate(timely_total=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG) |>
  summarise(DECODED,
            timely_total,
            timely_resistant = sum(DECODED == "Resistant" |
                                      DECODED == "Intermediate", na.rm = TRUE)) |>
  mutate(nonsusceptible=(timely_resistant/timely_total)) |>
  ungroup() |>
  group_by(ORGANISM_OR_BUG,
           DRUG,
           time) |>
  # selecting data for times with bug-drug combinations > 5
  filter(n()>5) |>
  ungroup() |>
  # adding levels for counts of total bug-drug combinations per time
  mutate(total_levels=as.factor(cut(timely_total, breaks = breaks))) |>
  distinct() |>  
  # left joining with drug classes
  left_join(
       #micro_cf_ALL |>
       micro_cf_BLOOD |>
            select(DRUG,
                   DRUG_CLASS) |>
            distinct(),
            by = "DRUG") |>
  mutate(DRUG = str_to_title(DRUG))  |>
  # removing duplicate rows
  select(ORGANISM_OR_BUG,
         time,
         DRUG,
         timely_total,
         nonsusceptible,
         total_levels) |>
  distinct()|>
  # reordering drugs panels to match x axis order of first resistance plot
  mutate(DRUG = factor(DRUG, levels = drugs_order)) |>
#View(),
  # plotting
  ggplot(aes(x=time,
             y=nonsusceptible,
             colour=ORGANISM_OR_BUG)) +
  #geom_point(aes(size=timely_total),
             #alpha=0.8) +
  geom_line(alpha=0.8) +
  labs(x = "Date",
       y = "Resistance (%)",
       colour = "Organism",
       size = "Quarterly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # legend text
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.background = element_blank()
       ) +
  facet_wrap(~DRUG) +
  scale_colour_manual(values = c("#008080","#FFA500","#708090"),
                     # making bug names italic
                     labels = c(expression(italic("Escherichia coli")),
                                expression(italic("Klebsiella pneumoniae")),
                                expression(italic("Other Enterobacteriaceae")))) +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1))+
  guides(colour = guide_legend(order = 1)) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) #+
  # second national lockdown date
  #geom_vline(xintercept=as.Date("2020-11-05"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8) +
  # third national lockdown date
  #geom_vline(xintercept=as.Date("2021-01-06"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8)

png(
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10a_micro_cf_ALL_resistance_line_chart.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10a_micro_cf_BLOOD_resistance_line_chart.jpeg",
       width=30,
       height=11.7,
       units="in",
       res=300
)
print(last_plot())
dev.off()

10b. line chart: all_data, bld_data¶

HO vs CO, Kpn or Ec only¶

In [ ]:
# line chart
#all_data |>
bld_data |>
  # filtering for bug of interest
  filter(
        ORGANISM_OR_BUG=="Escherichia coli" #|
        #ORGANISM_OR_BUG=="Klebsiella pneumoniae"
        ) |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # selecting columns of interest
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         WITHIN_SPELL,
         AFTER_48HRS,
         DRUG,
         DRUG_CLASS,
         DECODED) |>
  # creating time column
  mutate(time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering incomplete end month
  filter(time < end_date) |>
  # counting total bugs-drug combinations per time
  group_by(
           #ORGANISM_OR_BUG,
           HO,
           time,
           DRUG) |>
  # creating total timely count column
  mutate(timely_total=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(
           #ORGANISM_OR_BUG,
           HO,
           time,
           DRUG) |>
  summarise(DECODED,
            timely_total,
            timely_resistant = sum(DECODED == "Resistant" |
                                      DECODED == "Intermediate", na.rm = TRUE)) |>
  mutate(nonsusceptible=(timely_resistant/timely_total)) |>
  ungroup() |>
  group_by(
           #ORGANISM_OR_BUG,
           HO,
           DRUG,
           time) |>
  # selecting data for times with bug-drug combinations > 5
  filter(n()>5) |>
  ungroup() |>
  # adding levels for counts of total bug-drug combinations per time
  mutate(total_levels=as.factor(cut(timely_total, breaks = breaks))) |>
  distinct() |>  
  # left joining with drug classes
  left_join(
       micro_cf_ALL |>
       #micro_cf_BLOOD |>
            select(DRUG,
                   DRUG_CLASS) |>
            distinct(),
            by = "DRUG") |>
  mutate(DRUG = str_to_title(DRUG))  |>
  # removing duplicate rows
  select(
         #ORGANISM_OR_BUG,
         HO,
         time,
         DRUG,
         timely_total,
         nonsusceptible,
         total_levels) |>
  distinct()|>
  mutate(DRUG = factor(DRUG, levels = drugs_order)) |>
#View()
  # plotting
  ggplot(aes(x=time,
             y=nonsusceptible,
             colour=HO)) +
  #geom_point(aes(size=timely_total),
             #alpha=0.8) +
  geom_line(alpha=0.8) +
  labs(x = "Date",
       y = "Resistance (%)",
       colour = "Infection Category",
       size = "Yearly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.background = element_blank(),
          # plot title
          plot.title = element_text(hjust=0.5)
       ) +
  facet_wrap(~DRUG) +
  scale_colour_npg() +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  guides(colour = guide_legend(order = 1)) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1))+
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) #+
  # second national lockdown date
  #geom_vline(xintercept=as.Date("2020-11-05"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8) +
  # third national lockdown date
  #geom_vline(xintercept=as.Date("2021-01-06"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8) +
  #ggtitle("Kpn ONLY")

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_all_data_resistance_HO_vs_CO_Kpn_ONLY_line_chart.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_bld_data_resistance_HO_vs_CO_Kpn_ONLY_line_chart.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_all_data_resistance_HO_vs_CO_Ec_ONLY_line_chart.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_bld_data_resistance_HO_vs_CO_Ec_ONLY_line_chart.jpeg",
       width=30,
       height=11.7,
       units="in",
       res=300
)
print(last_plot())
dev.off()

11. bar chart overall resistance CHECKED & READY¶

In [ ]:
# bar chart
micro_cf_ALL |>
#micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # selecting columns of interest
  select(SUBJECT,
         ORGANISM_OR_BUG,
         DRUG,
         DRUG_CLASS,
         DECODED) |>
  # counting total bugs-drug combinations
  group_by(ORGANISM_OR_BUG,
           DRUG) |>
  mutate(totalcombinations=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(ORGANISM_OR_BUG,
           DRUG) |>
  summarise(DECODED,
            totalcombinations,
            resistant = sum(DECODED == "Resistant" |
                            DECODED == "Intermediate", na.rm = TRUE)) |>
  distinct() |>
  mutate(nonsusceptible=(resistant/totalcombinations)) |>
  ungroup() |>
  # selecting data bug-drug combinations > 5
  filter(totalcombinations>5) |>
  ungroup() |>
  select(ORGANISM_OR_BUG,
         DRUG,
         nonsusceptible) |>
  distinct() |>  
  # left joining with drug classes
  left_join(
       #micro_cf_ALL |>
       micro_cf_BLOOD |>
            select(DRUG,
                   DRUG_CLASS) |>
            distinct(),
            by = "DRUG") |>
  # removing capitalisation of drug names
  mutate(DRUG = str_to_title(DRUG)) |>
  # plotting
  ggplot(aes(x=DRUG,
             y=nonsusceptible,
             fill=DRUG_CLASS)) +
  geom_col(alpha=0.8) +
  labs(x = "Drug",
       y = "Resistance (%)",
       fill = "Drug Class",
       size = "Monthly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11, face = "italic"),
          strip.background = element_blank(),
          axis.title.x = element_text(vjust=2),
        axis.text.x = element_text(angle=45,hjust=1)) +
  scale_y_continuous(labels=scales::percent_format(scale=100)) +
  facet_wrap(~ORGANISM_OR_BUG) +
  scale_fill_aaas() +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  guides(fill = guide_legend(order = 1)) +
  # first national lockdown date
  geom_hline(yintercept=0.1,
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  scale_x_discrete(limit = c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )) +
  scale_fill_manual(values = c(
       "Aminoglycosides"="#3B4992CC",
       "Carbapenems"="#EE0000CC",
       "Cephalosporins"="#008B45CC",
       "Fluoroquinolones"="#631879CC",
       "Penicillins"="#5F559BCC",
       "Sulfonamides"="#A20056CC"
  ))


ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/3_03062025/11_micro_cf_ALL_resistance_bar_chart_03062025.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/3_03062025/11_micro_cf_BLOOD_resistance_bar_chart_03062025.jpeg",
       height= 4,
       width=16)

11. bar chart (HO vs CO)¶

In [ ]:
# bar chart
all_data |>
#bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae"),
          # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # selecting columns of interest
  select(SUBJECT,
         ORGANISM_OR_BUG,
         DRUG,
         HO,
         DECODED) |>
  # counting total bugs-drug combinations
  group_by(ORGANISM_OR_BUG,
           DRUG,
           HO) |>
  mutate(totalcombinations=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(ORGANISM_OR_BUG,
           DRUG,
           HO) |>
  summarise(DECODED,
            totalcombinations,
            resistant = sum(DECODED == "Resistant" |
                            DECODED == "Intermediate", na.rm = TRUE)) |>
  distinct() |>
  mutate(nonsusceptible=(resistant/totalcombinations)) |>
  ungroup() |>
  # selecting data bug-drug combinations > 5
  filter(totalcombinations>5) |>
  ungroup() |>
  select(ORGANISM_OR_BUG,
         DRUG,
         HO,
         nonsusceptible) |>
  distinct() |>
  # removing capitalisation of drug names
  mutate(DRUG = str_to_title(DRUG)) |>
  # plotting
  ggplot(aes(x=DRUG,
             y=nonsusceptible,
             fill=HO)) +
  geom_col(alpha=0.8, position = "dodge") +
  labs(x = "Drug",
       y = "Resistance (%)",
       fill = "Infection Category",
       size = "Monthly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11, face = "italic"),
          strip.background = element_blank(),
          axis.title.x = element_text(vjust=2),
        axis.text.x = element_text(angle=45,hjust=1)) +
  scale_y_continuous(labels=scales::percent_format(scale=100)) +
  facet_wrap(~ORGANISM_OR_BUG) +
  scale_fill_aaas() +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  guides(fill = guide_legend(order = 1)) +
  # first national lockdown date
  geom_hline(yintercept=0.1,
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  scale_x_discrete(limit = c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )) +
  scale_fill_npg()

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/11_micro_cf_ALL_resistance_HO_vs_CO_bar_chart_03062025.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/11_micro_cf_BLOOD_resistance_HO_vs_CO_bar_chart.jpeg",
       width=16,
       height=4,
       units="in",
       res=300
)
print(last_plot())
dev.off()

11. bar chart (Kpn blood isolates, April 2020 - December 2021)¶

In [ ]:
# bar chart
micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG == "Klebsiella pneumoniae") |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # filtering for April 2020 - December 2021
  filter(SAMPLE_COLLECTED_DT >= as.Date("2020-04-01") & SAMPLE_COLLECTED_DT <= as.Date("2021-12-31")) |>
  # selecting columns of interest
  select(SUBJECT,
         ORGANISM_OR_BUG,
         DRUG,
         DRUG_CLASS,
         DECODED) |>
  # counting total bugs-drug combinations
  group_by(ORGANISM_OR_BUG,
           DRUG) |>
  mutate(totalcombinations=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(ORGANISM_OR_BUG,
           DRUG) |>
  summarise(DECODED,
            totalcombinations,
            resistant = sum(DECODED == "Resistant" |
                            DECODED == "Intermediate", na.rm = TRUE)) |>
  distinct() |>
  mutate(nonsusceptible=(resistant/totalcombinations)) |>
  ungroup() |>
  # selecting data bug-drug combinations > 5
  filter(totalcombinations>5) |>
  ungroup() |>
  select(ORGANISM_OR_BUG,
         DRUG,
         nonsusceptible) |>
  distinct() |>  
  # left joining with drug classes
  left_join(
       #micro_cf_ALL |>
       micro_cf_BLOOD |>
            select(DRUG,
                   DRUG_CLASS) |>
            distinct(),
            by = "DRUG") |>
  # removing capitalisation of drug names
  mutate(DRUG = str_to_title(DRUG)) |>
  # plotting
  ggplot(aes(x=DRUG,
             y=nonsusceptible,
             fill=DRUG_CLASS)) +
  geom_col(alpha=0.8) +
  labs(x = "Drug",
       y = "Resistance (%)",
       fill = "Drug Class",
       size = "Monthly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11, face = "italic"),
          strip.background = element_blank(),
          axis.title.x = element_text(vjust=2),
        axis.text.x = element_text(angle=45,hjust=1)) +
  scale_y_continuous(labels=scales::percent_format(scale=100)) +
  #facet_wrap(~ORGANISM_OR_BUG) +
  scale_fill_aaas() +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  guides(fill = guide_legend(order = 1)) +
  # first national lockdown date
  geom_hline(yintercept=0.1,
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  scale_x_discrete(limit = c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )) +
  scale_fill_manual(values = c(
       "Aminoglycosides"="#3B4992CC",
       "Carbapenems"="#EE0000CC",
       "Cephalosporins"="#008B45CC",
       "Fluoroquinolones"="#631879CC",
       "Penicillins"="#5F559BCC",
       "Sulfonamides"="#A20056CC"
  ))

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       width=5.33,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

11. bar chart (Kpn blood isolates, April 2020 - December 2021, HO vs CO)¶

In [ ]:
# bar chart
bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG == "Klebsiella pneumoniae") |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # filtering for April 2020 - December 2021
  filter(SAMPLE_COLLECTED_DT >= as.Date("2020-04-01") & SAMPLE_COLLECTED_DT <= as.Date("2021-12-31")) |>
  mutate(
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # selecting columns of interest
  select(SUBJECT,
         ORGANISM_OR_BUG,
         DRUG,
         HO,
         DECODED) |>
  # counting total bugs-drug combinations
  group_by(ORGANISM_OR_BUG,
           DRUG,
           HO) |>
  mutate(totalcombinations=n()) |>
  ungroup() |>
  # creating non-susceptible column
  group_by(ORGANISM_OR_BUG,
           DRUG,
           HO) |>
  summarise(DECODED,
            totalcombinations,
            resistant = sum(DECODED == "Resistant" |
                            DECODED == "Intermediate", na.rm = TRUE)) |>
  distinct() |>
  mutate(nonsusceptible=(resistant/totalcombinations)) |>
  ungroup() |>
  # selecting data bug-drug combinations > 5
  filter(totalcombinations>5) |>
  ungroup() |>
  select(ORGANISM_OR_BUG,
         DRUG,
         HO,
         nonsusceptible) |>
  distinct() |>
  # removing capitalisation of drug names
  mutate(DRUG = str_to_title(DRUG)) |>
  # plotting
  ggplot(aes(x=DRUG,
             y=nonsusceptible,
             fill=HO)) +
  geom_col(alpha=0.8, position = "dodge") +
  labs(x = "Drug",
       y = "Resistance (%)",
       fill = "Infection Category",
       size = "Monthly Count") +
  theme_bw() +
  theme(
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11, face = "italic"),
          strip.background = element_blank(),
          axis.title.x = element_text(vjust=2),
        axis.text.x = element_text(angle=45,hjust=1)) +
  scale_y_continuous(labels=scales::percent_format(scale=100)) +
  #facet_wrap(~ORGANISM_OR_BUG) +
  scale_fill_aaas() +
  scale_size_binned(breaks = breaks,
                    range = c(0.5, 4)) +
  guides(fill = guide_legend(order = 1)) +
  # first national lockdown date
  geom_hline(yintercept=0.1,
             linetype = "dashed",
             color = "grey",
             alpha=0.8) +
  scale_x_discrete(limit = c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )) +
  scale_fill_npg()

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       width=6,
       height=3,
       units="in",
       res=300
)
print(last_plot())
dev.off()

<<< 4. TIME SERIES MODELLING >>>¶

determining which drugs to choose for analyses¶

checking coverage of bug-drug combinations¶

In [ ]:
#micro_cf_ALL |>
#all_data |>
#micro_cf_BLOOD |>
bld_data |>
  # filtering for bugs of interest
  filter(ORGANISM_OR_BUG=="Escherichia coli" |
           ORGANISM_OR_BUG=="Klebsiella pneumoniae") |>
  # filtering for drugs of interest
  filter(DRUG_CLASS != "Other") |>
  count(DRUG,ORGANISM_OR_BUG) |>
  spread(ORGANISM_OR_BUG,n) |>
  arrange(desc(`Klebsiella pneumoniae`),desc(`Escherichia coli`))

aminoglycosides: gentamicin (excellent coverage), amikacin (excellent coverage)¶

carbapenems: meropenem (excellent coverage), ertapenem (excellent coverage), imipenem (poor coverage - REMOVED 17/04/2025)¶

ESBL: cefotaxime (ok coverage, REMOVED 28/04/2025), ceftriaxone (excellent coverage), ceftazidime (excellent coverage), cefepime (poor coverage - REMOVED 17/04/2025), amoxycillin (excellent coverage - ADDED 17/04/2025), co-amoxiclav (excellent coverage - ADDED 17/04/2025 )¶

potential CPE: tazocin (piperacillin-tazobactam) (excellent coverage), temocillin (excellent coverage), ciprofloxacin (excellent coverage), cotrimoxazole (trimethoprim-sulfamethoxazole) (ok coverage)¶

In [ ]:
# creating filtering vector for drugs clinically relevant in Kpn bacteraemia
drugs_of_interest <- c("GENTAMICIN","AMIKACIN",
                       "MEROPENEM","ERTAPENEM",
                       "CEFTRIAXONE","CEFTAZIDIME", "AMOXYCILLIN","CO-AMOXICLAV",
                       "TAZOCIN","TEMOCILLIN","CIPROFLOXACIN","COTRIMOXAZOLE")

exploring changes pre- and post-national lockdowns for interrupted analysis¶

model data: micro_cf_ALL or micro_cf_BLOOD as these are the most complete microbiology susceptibility testing data sets¶

use of scaled predictors:¶

helps convergence of glmer() and other mixed models¶

makes interaction terms (e.g., time:tp1) more stable¶

lets us interpret coefficients in terms of SD units, not raw time units, e.g., for each SD of time, log-odds increase/decrease by coefficient value¶

In [ ]:
model_data <-
#micro_cf_ALL |>
micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # filtering for drugs of interest
  filter(DRUG %in% drugs_of_interest) |>
  # creating month column
  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month")) |>
  # filtering incomplete end month
  filter(month < end_date) |>
  # counting total bugs-drug combinations per month
  group_by(ORGANISM_OR_BUG,
           month,
           DRUG) |>
  # creating total monthly count column
  mutate(monthly_total=n()) |>
  # selecting data for months with bug-drug combinations > 5
  filter(monthly_total > 5) |>
  # creating non-susceptible column
  summarise(DECODED,
            monthly_total,
            monthly_resistant = sum(DECODED == "Resistant" |
                                    DECODED == "Intermediate", na.rm = TRUE)) |>
  ungroup() |>
  # creating nonsusceptible column
  mutate(nonsusceptible=(monthly_resistant/monthly_total)*100) |>
  # arranging by month
  arrange(month) |>
  # creating model terms
  mutate(time = as.numeric(difftime(month, min(month),max(month),unit = "days")) / 30.44, # average days per month
         # rounding
         time = round(time,1),
         # lockdown 1 date
         ld1 = as.Date("2020-03-23"),
         # lockdown 2 date
         ld2 = as.Date("2020-11-05"),
         # lockdown 3 date
         ld3 = as.Date("2021-01-06"),
         # time post lockdown 1
         tp1 = if_else(month >= ld1, time - as.numeric(difftime(ld1, min(month), unit = "days")) / 30.44, 0), # converting time to months since lockdown 1
         # time post lockdown 2
         tp2 = if_else(month >= ld2, time - as.numeric(difftime(ld2, min(month), unit = "days")) / 30.44, 0),
         # time post lockdown 3
         tp3 = if_else(month >= ld3, time - as.numeric(difftime(ld3, min(month), unit = "days")) / 30.44, 0)) |>
  # rescaling predictors
  mutate(across(c(time, tp1, tp2, tp3), scale)) |>
  distinct()
# viewing model data
kable(model_data)

<<< SAVING MODEL DATA FOR FURTHER WORK (OFF ICARE) >>>¶

In [ ]:
# model_data_micro_cf_ALL - DONE
# model_data_micro_cf_BLOOD - DONE
#write_xlsx(model_data, "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/model_data_micro_cf_BLOOD_29052025.xlsx")

glmer()¶

working model: glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * (tp1 + tp2 + tp3) + (1|ORGANISM_OR_BUG:DRUG))¶

cbind(monthly_resistant, monthly_total - monthly_resistant): for each bug:drug combination in a given month, there is a number of resistant isolates out of a total number of isolates tested; we are modelling the probability of resistance in binomial framework¶

time: baseline trend - in log odds - of resistance over time, before lockdown 1¶

tpX: immediate step change - in log odds - of resistance at lockdown X¶

time:tpX: change in trend after lockdown X; e.g., did the slope of the time trend change after lockdown X?¶

(1|ORGANISM_OR_BUG:DRUG): random intercept for each bug-drug combination; accounts for baseline differences in resistance levels across different bug:drug combinations¶

model¶

In [ ]:
interrupted_ts <- glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * (tp1 + tp2 + tp3) + (1|ORGANISM_OR_BUG:DRUG),
                        data = model_data, 
                        family = "binomial")

model selection¶

avoiding rules to prevent biasing model selection¶

In [ ]:
options(na.action = "na.fail")

model_set <- dredge(interrupted_ts)

kable(model_set)

testing model assumptions¶

In [ ]:
# qqplot of random intercepts
## straight line = perfectly normal
## plots shows approximate normality of random effects (deviation at tails)
lattice::qqmath(ranef(interrupted_ts, condVar = TRUE))
## plot not showing here for some reason - looked ok at last check

# heteroscedasticity
## residuals show varying spread across different fitted values
plot(interrupted_ts)

model summary¶

In [ ]:
summary(get.models(model_set, 1)[[1]])

intercept: baseline log odds at time 0, before lockdown 1¶

time: baseline trend in log odds¶

tp1: immediate step change at lockdown 1¶

tp2: immediate step change at lockdown 2¶

tp3: immediate step change at lockdown 3¶

time:tp1: change in trend post lockdown 1¶

time:tp2: change in trend post lockdown 2¶

time:tp3: change in trend post lockdown 3¶

glm()¶

looking at bug:drug combinations separately¶

testing for normality across bug-drug combinations¶

In [ ]:
model_data_test <- model_data |>
    group_by(DRUG, ORGANISM_OR_BUG) |>
    summarise(
        n = n(),
        p = if_else(n>=3,shapiro.test(nonsusceptible)$p.value, NA_real_)
    )

# non-normal if p < 0.05
kable(model_data_test |>
        filter(p > 0.05))
## therefore, 4/24 normal

plotting for normality across bug-drug combinations¶

In [ ]:
ggplot(model_data,
    aes(x=nonsusceptible)) +
    geom_histogram() +
    facet_wrap(~ interaction(DRUG,ORGANISM_OR_BUG), scales = "free_y")

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       height= 10,
       width=20)

working model across both micro_cf_ALL and micro_cf_BLOOD: glm(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1¶

including tp1, tp2, & tp3 at bug:drug level, we risk overfitting, colinearity, and a lack of statistical power to detect changes here¶

lockdowns 1, 2, & 3 were relatively close together in time, when in the context of the wider data set (~10 years), therefore, including only lockdown 1 (time post lockdown 1; tp1) appears a statistically cleaner choice¶

the first lockdown likely corresponds to the biggest health disruption, the strongest public health response, and the most important change in behaviour¶

In [ ]:
# splitting by  bug-drug combination
models <- model_data |>
    ungroup() |>
    group_by(DRUG, ORGANISM_OR_BUG) |>
    group_split()

# generating model names list
model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), ": ", str_to_title(.x$ORGANISM_OR_BUG[1])))

# naming the models
named_models <- set_names(models, model_names)

# fitting models and computing acf
fitted_models <-
    map(named_models, ~glm(
        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1,
        data = .x,
        family = "binomial"
    ))

# model summaries
model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>
                           mutate(aic = AIC(.x),
                                  deviance = deviance(.x),
                                  n_obs = nobs(.x)), .id = "Drug: Bug")

# acf summaries
acf_summary <- map_dfr(fitted_models, function(model) {
     resids <- resid(model, type = "pearson")
     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf
     
     tibble(
            lag1_auto = acf_vals[2],
            lag2_auto = acf_vals[3],
            lag3_auto = acf_vals[4],
        )

}, .id = "Drug: Bug")

all_summaries <- left_join(model_summaries, acf_summary, by = "Drug: Bug")

viewing summaries data¶

In [ ]:
kable(all_summaries)

as we can see from the lag1_auto column, month-to-month dependence is non-negligible¶

therefore, we ought to account for this autocorrelation by creating a lagged predictor that represents the previous months resistance¶

In [ ]:
# splitting by  bug-drug combination
models <- model_data |>
    ungroup() |>
    group_by(DRUG, ORGANISM_OR_BUG) |>
    # ensuring time ordering within each group
    arrange(time, .by_group = TRUE) |>
    # adding lagged predictor
    mutate(lag1_resistance = lag(monthly_resistant / monthly_total, n=1)) |>
    group_split()

# generating model names list
model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), ": ", str_to_title(.x$ORGANISM_OR_BUG[1])))

# naming the models
named_models <- set_names(models, model_names)

# fitting models and computing acf
fitted_models <-
    map(named_models, ~glm(
        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 + lag1_resistance,
        # removing NA lagged values which will hinder model fit
        data = drop_na(.x, lag1_resistance),
        family = "binomial"
    ))

# model summaries
model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>
                           mutate(aic = AIC(.x),
                                  deviance = deviance(.x),
                                  n_obs = nobs(.x)), .id = "Drug: Bug")

# acf summaries
acf_summary <- map_dfr(fitted_models, function(model) {
     resids <- resid(model, type = "pearson")
     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf
     
     tibble(
            lag1_auto = acf_vals[2],
            lag2_auto = acf_vals[3],
            lag3_auto = acf_vals[4],
        )

}, .id = "Drug: Bug")

all_summaries <- left_join(model_summaries, acf_summary, by = "Drug: Bug")

viewing summaries data¶

AIC and deviance drop dramatically, indicating better model fit¶

lag1_auto correlation decreases¶

lag1_resistance term significant, supporting its explanatory power¶

therefore, overall, model better captures momentum/inertia¶

In [ ]:
kable(all_summaries)

plotting model summaries¶

12. model terms plot version 1¶

In [ ]:
model_summaries |>
    # selecting model terms of interest
    filter(
    term != "(Intercept)" &
    term != "lag1_resistance"
    #"time"
    #"tp1"
    #"time:tp1"
    ) |>
    # filtering for significance
    #filter(p.value < 0.05) |>
    # converting to OR
    mutate(OR = exp(estimate),
           OR_low = exp(estimate - 1.96 * std.error),
           OR_high = exp(estimate + 1.96 * std.error),
           sign = if_else(OR < 1, "-ve", "+ve"),
           # reordering factor levels
           term = factor(term, levels = c("time","tp1","time:tp1")),
           # recoding factors
           term = recode(term, 
                         "time"="Baseline Trend",
                         "tp1"="Immediate Step Change\nAt Intervention",
                         "time:tp1"="Change In Baseline Trend\nFollowing Intervention")) |>
       # separating Drug: Bug column
       separate(`Drug: Bug`, into =c("Drug","Bug"), sep = ":\\s*")  |>
    # making second word in Bug column lower case
    mutate(Bug = str_split_fixed(Bug, " ", 2)) |>
    mutate(Bug = paste0(Bug[,1], " ", str_to_lower(Bug[,2]))) |>
    # filtering for finite and non-negative values
    filter(is.finite(OR) &
            OR > 0) |>
    # plotting
    ggplot(aes(
               x=Drug,
               y=OR,
               colour=Bug
               )) +
    # enabling log and linear scales simultaneously
    scale_y_log10(breaks = c(0,0.1,0.2,0.5,1,2,5,10
                 ),
                  labels = label_number()) +
    geom_point(size = 1, position = position_dodge(width=0.5)) +
    geom_errorbar(aes(ymin = OR_low,
                      ymax = OR_high),
                  alpha = 0.5,
                  width = 0.4,
                  position = position_dodge(width=0.5)) +
    theme_bw() +
    # comment out to view mega extremes
    labs(x="",
         colour="Organism",
         y="Odds Ratio (Log Scale)") +
    geom_hline(yintercept = 1, linetype = "dashed",colour="grey") +
    scale_colour_manual(values = c("#008080","#FFA500")) +
    theme(axis.title.x = element_blank(),
          axis.title.y = element_text(vjust = 2),
          axis.text.x = element_text(angle=45,hjust=1),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.background = element_blank(),
          # margin
          plot.margin = margin(1,1,1,40, unit = "pt")) +
    facet_wrap(~term)

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_ALL_OR_model_terms.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_BLOOD_OR_model_terms.jpeg",
       height= 5,
       width=14)

12. model terms plot version 2¶

In [ ]:
model_summaries |>
    # selecting model terms of interest
    filter(
    term != "(Intercept)" &
    term != "lag1_resistance"
    #"time"
    #"tp1"
    #"time:tp1"
    ) |>
    # filtering for significance
    #filter(p.value < 0.05) |>
    # converting to OR
    mutate(OR = exp(estimate),
           OR_low = exp(estimate - 1.96 * std.error),
           OR_high = exp(estimate + 1.96 * std.error),
           sign = if_else(OR < 1, "-ve", "+ve"),
           # reordering factor levels
           term = factor(term, levels = c("time","tp1","time:tp1")),
           # recoding factors
           term = recode(term, 
                         "time"="Baseline Trend",
                         "tp1"="Immediate Step Change\nAt Intervention",
                         "time:tp1"="Change In Baseline Trend\nFollowing Intervention")) |>
       # separating Drug: Bug column
       separate(`Drug: Bug`, into =c("Drug","Bug"), sep = ":\\s*") |>
    # making second word in Bug column lower case
    mutate(Bug = str_split_fixed(Bug, " ", 2)) |>
    mutate(Bug = paste0(Bug[,1], " ", str_to_lower(Bug[,2]))) |>
    # filtering for finite and non-negative values
    filter(is.finite(OR) &
            OR > 0) |>
    # plotting
    ggplot(aes(
               x=term,
               y=OR,
               group=Drug,
               colour=Drug
               )) +
    # enabling log and linear scales simultaneously
    scale_y_log10(breaks = c(0.0,0.1,0.2,0.5,1,2,5,10
                 ),
                  labels = label_number()) +
    geom_point(size = 1,position = position_dodge(width=0.5)) +
    #geom_line(linewidth = 0.3, alpha = 0.8, position = position_dodge(width=0.5)) +
    geom_errorbar(aes(ymin = OR_low,
                      ymax = OR_high),
                  alpha = 0.5,
                  width = 0.4,
                  position = position_dodge(width=0.5)) +
    theme_bw() +
    labs(x="",
         colour="Drug",
         y="Odds Ratio (Log Scale)") +
    geom_hline(yintercept = 1, linetype = "dashed",colour="grey") +
    scale_colour_igv() +
    theme(axis.title.x = element_blank(),
          axis.title.y = element_text(vjust = 2),
          axis.text.x = element_text(angle=45,hjust=1),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.background = element_blank(),
          # margin
          plot.margin = margin(1,1,1,40, unit = "pt")) +
    facet_wrap(~Bug)

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_ALL_OR_model_terms_v2.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_BLOOD_OR_model_terms_v2.jpeg",
       height= 7,
       width=14)

Log Odds¶

Log Odds ~0: No effect¶

**Log Odds > 0 **: Increase in probability (positive effect; e.g., odds double at log odds = 0.7 since exp(0.7)=2)¶

**Log Odds < 0 **: Decrease in probability (negative effect; e.g., odds halve at log odds = -0.7 since exp(-0.7)=0.5)¶

Use exp(Log Odds) to generate Odds Ratio (OR)¶

OR ~1.0: No real effect¶

OR > 1: Odds increased¶

OR < 1: Odds decreased¶

OR > 1.2 or OR < 0.8: small but real effect¶

OR > 2 or OR < 0.5: large effect¶

Confidence Intervals¶

95% CI overlapping 1: Not statistically significant¶

Wide CI: Low certainty, likely due to a small n¶

hence¶

1. for most bug:drug combinations, resistance was increasing over time (+ve slope), before intervention¶

2. for most bug:drug combinations, there was an immediate step decrease in resistance following intervention (tp1)¶

3. for most bug:drug combinations, there was a subsequent increase in resistance slope post intervention (time:tp1)¶

exploring differences in trends across CO vs HO infections¶

model data: all_data or bld_data as microbiology have been matched to patient data¶

In [ ]:
model_data <-
#all_data |>
bld_data |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # filtering for drugs of interest
  filter(DRUG %in% drugs_of_interest) |>
  # creating month column
  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering incomplete end month
  filter(month < end_date) |>
  # counting total bugs-drug combinations per month
  group_by(ORGANISM_OR_BUG,
           HO,
           month,
           DRUG) |>
  # creating total monthly count column
  mutate(monthly_total=n()) |>
  # selecting data for months with bug-drug combinations > 5
  filter(monthly_total > 5) |>
  # creating non-susceptible column
  summarise(DECODED,
            monthly_total,
            monthly_resistant = sum(DECODED == "Resistant" |
                                    DECODED == "Intermediate", na.rm = TRUE)) |>
  ungroup() |>
  # creating nonsusceptible column
  mutate(nonsusceptible=(monthly_resistant/monthly_total)*100) |>
  # arranging by month
  arrange(month) |>
  # creating model terms
  mutate(time = as.numeric(difftime(month, min(month),max(month),unit = "days")) / 30.44, # average days per month
         # rounding
         time = round(time,1),
         # lockdown 1 date
         ld1 = as.Date("2020-03-23"),
         # lockdown 2 date
         ld2 = as.Date("2020-11-05"),
         # lockdown 3 date
         ld3 = as.Date("2021-01-06"),
         # time post lockdown 1
         tp1 = if_else(month >= ld1, time - as.numeric(difftime(ld1, min(month), unit = "days")) / 30.44, 0), # converting time to months since lockdown 1
         # time post lockdown 2
         tp2 = if_else(month >= ld2, time - as.numeric(difftime(ld2, min(month), unit = "days")) / 30.44, 0),
         # time post lockdown 3
         tp3 = if_else(month >= ld3, time - as.numeric(difftime(ld3, min(month), unit = "days")) / 30.44, 0),
         # onset term
         HO = relevel(factor(HO), ref = "Community Onset")
         ) |>
  # rescaling predictors
  mutate(across(c(time, tp1, tp2, tp3), scale)) |>
  distinct()
# viewing model data
kable(model_data)

<<< SAVING MODEL DATA FOR FURTHER WORK (OFF ICARE) >>>¶

In [ ]:
# model_data_all_data - DONE
# model_data_bld_data - DONE
#write_xlsx(model_data, "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/model_data_bld_data_29052025.xlsx")

model selection¶

In [ ]:
# working model
interrupted_ts_onsetterm <- glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 * HO + (1|ORGANISM_OR_BUG:DRUG),
                                        data = model_data, 
                                        family = "binomial")

                        options(na.action = "na.fail")

# model selection
model_set <- dredge(interrupted_ts_onsetterm)

model summary¶

In [ ]:
summary(get.models(model_set, 1)[[1]])

intercept: baseline log odds at time 0, before lockdown 1, for CO reference group¶

time: baseline trend in resistance, before lockdown 1, for CO reference group¶

tp1: immediate step change at lockdown 1 for CO reference group¶

HOHospital Onset: difference in baseline log odds at time 0, before lockdown 1, between HO group and CO reference group¶

HOHospital Onset:time: difference in trend in resistance, before lockdown 1, between HO group and CO reference group¶

HOHospital Onset:tp1: difference in immediate step change at lockdown 1 between HO group and CO reference group¶

time:tp1: change in trend post lockdown 1 (compared to baseline) for CO reference group¶

HOHospital Onset:time:tp1: difference in change in trend post lockdown 1 between HO group and CO reference group¶

model inferences¶

all_data¶

intercept: exp(-0.49) = 0.61 = the odds of resistance at baseline for CO infections¶

time: resistance was increasing over time for CO infections¶

tp1: drop in resistance for CO infections following lockdown 1¶

HOHospital Onset: exp(0.46) = 1.58 = 58% higher odds of resistance at baseline for HO infectiosn¶

HOHospital Onset:time: resistance was increasing more slowly over time for HO infections¶

HOHospital Onset:tp1: drop in resistance was smaller for HO infections following lockdown 1¶

time:tp1: trend increased more steeply post lockdown 1 (compared to baseline) for CO infections¶

HOHospital Onset:time:tp1: trends increased even more steeply post lockdown 1 for HO infections¶

bld_data¶

intercept: exp(-0.76) = 0.47 = the odds of resistance at baseline for CO infections¶

time: resistance was increasing over time for CO infections¶

tp1: drop in resistance for CO infections following lockdown 1¶

HOHospital Onset: exp(0.49) = 1.63 = 63% higher odds of resistance at baseline for HO infections¶

HOHospital Onset:time: resistance was increasing more slowly over time for HO infections¶

HOHospital Onset:tp1: drop in resistance was smaller for HO infections following lockdown 1¶

time:tp1: trend increased more steeply post lockdown 1 (compared to baseline) for CO infections¶

HOHospital Onset:time:tp1: trends increased even more steeply post lockdown 1 for HO infections¶

looking at bug:drug combinations and HO versus CO infections separately¶

In [ ]:
# splitting by  bug-drug combination
models <- model_data |>
    ungroup() |>
    group_by(DRUG, ORGANISM_OR_BUG) |>
    # ensuring time ordering within each group
    arrange(time, .by_group = TRUE) |>
    # adding lagged predictor
    mutate(lag1_resistance = lag(monthly_resistant / monthly_total, n=1)) |>
    group_split()

# generating model names list
model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), ": ",
                                        str_to_title(.x$ORGANISM_OR_BUG[1]), ": ",
                                        str_to_title(.x$HO[1])))

# naming the models
named_models <- set_names(models, model_names)

# fitting models and computing acf
fitted_models <-
    map(named_models, ~glm(
        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 * HO + lag1_resistance,
        # removing NA lagged values which will hinder model fit
        data = drop_na(.x, lag1_resistance),
        family = "binomial"
    ))

# model summaries
model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>
                           mutate(aic = AIC(.x),
                                  deviance = deviance(.x),
                                  n_obs = nobs(.x)), .id = "Drug: Bug: Onset")

# acf summaries
acf_summary <- map_dfr(fitted_models, function(model) {
     resids <- resid(model, type = "pearson")
     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf
     
     tibble(
            lag1_auto = acf_vals[2],
            lag2_auto = acf_vals[3],
            lag3_auto = acf_vals[4],
        )

}, .id = "Drug: Bug: Onset")

all_summaries <- left_join(model_summaries, acf_summary, by = "Drug: Bug: Onset")

viewing summaries data¶

In [ ]:
kable(all_summaries)

plotting model summaries¶

13. model terms plot version 2¶

In [ ]:
all_summaries |>
    # selecting model terms of interest
    filter(term !="(Intercept)" &
           term != "HOHospital Onset" &
           term !="lag1_resistance"
    #"time"
    #"tp1"
    #"time:tp1"
    ) |>
    # converting to OR
    mutate(OR = exp(estimate),
           OR_low = exp(estimate - 1.96 * std.error),
           OR_high = exp(estimate + 1.96 * std.error),
           sign = if_else(OR < 1, "-ve", "+ve"),
           # reordering factor levels
           term = factor(term, levels = c("time","tp1","time:tp1","time:HOHospital Onset","tp1:HOHospital Onset","time:tp1:HOHospital Onset")),
           # recoding factors
           term = recode(term, 
                         "time"="Baseline Trend",
                         "tp1"="Immediate Step Change\nat Intervention",
                         "time:tp1"="Change in Baseline Trend\nFollowing Intervention",
                         "time:HOHospital Onset"="Difference\nin Baseline Trend",
                         "tp1:HOHospital Onset"="Difference in\nImmediate Step Change\nAt Intervention",
                         "time:tp1:HOHospital Onset"="Difference\nin Change in Baseline\nTrend Following Intervention")) |>
    # separating Drug: Bug column
    separate(`Drug: Bug: Onset`, into =c("Drug","Bug","Onset"), sep = ":\\s*") |>
    # making second word in Bug column lower case
    mutate(Bug = str_split_fixed(Bug, " ", 2)) |>
    mutate(Bug = paste0(Bug[,1], " ", str_to_lower(Bug[,2]))) |>
    # filtering for finite and non-negative values
    filter(is.finite(OR) &
            OR > 0)
    
In [ ]:
# plotting
    ggplot(aes(
               x=term,
               y=OR,
               group=Drug,
               colour=Drug
               )) +
    # enabling log and linear scales simultaneously
    scale_y_log10(labels = label_number()) +
    geom_point(size = 1,position = position_dodge(width=0.5)) +
    #geom_line(linewidth = 0.3, alpha = 0.8, position = position_dodge(width=0.5)) +
    geom_errorbar(aes(ymin = OR_low,
                      ymax = OR_high),
                  alpha = 0.5,
                  width = 0.4,
                  position = position_dodge(width=0.5)) +
    theme_bw() +
    labs(x="",
         colour="Drug",
         y="Odds Ratio (Log Scale)") +
    geom_hline(yintercept = 1, linetype = "dashed",colour="grey") +
    scale_colour_igv() +
    theme(axis.title.x = element_blank(),
          axis.title.y = element_text(vjust = 2),
          axis.text.x = element_text(angle=45,hjust=1),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.background = element_blank(),
          # margin
          plot.margin = margin(1,1,1,40, unit = "pt")) +
    facet_grid(~Bug)

ggsave(plot=last_plot(),
       "/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/13_all_data_HO_vs_CO_OR_model_terms_v2.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/13_bld_data_HO_vs_CO_OR_model_terms_v2.jpeg",
       height= 7,
       width=14)

<<< 5. ARIMA >>>¶

1_time_series_modelling.Rmd¶

<<< 6. COMPARISONS WITH NATIONAL DATA >>>¶

loading national data¶

In [ ]:
# espaur data
espaur_data <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/ESPAUR_data.csv")
head(espaur_data)

# ukhsa data
ukhsa_data <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/UKHSA_Apr2020-Mar2022.csv")
head(ukhsa_data)

joining espaur data with micro_cf_BLOOD data¶

tidying espaur data¶

In [ ]:
espaur_data <- 
    espaur_data |>
    # selecting columns of interest as they relate to the micro_cf_BLOOD data
    select(ORGANISM_OR_BUG=Bug, 
           DRUG_CLASS=Drug,
           time=Year,
           total_CLASS=total.isolates,
           resistant_CLASS=total.resistant.isolates
           ) |>
    # reclassifying columns
    mutate(ORGANISM_OR_BUG = as.factor(ORGANISM_OR_BUG),
           DRUG_CLASS = as.factor(str_to_title(DRUG_CLASS)),
           total_CLASS = as.integer(gsub(",", "", total_CLASS)),
           resistant_CLASS = as.integer(gsub(",","", resistant_CLASS))) |>
    # changing pip-taz to TAZOCIN
    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,"Piperacillin With Tazobactam", "Tazocin")) |>
    # reclassifying date column
    mutate(time = as.Date(paste0(time,"-01-01"))) |>
    # removing note annotations
    mutate(DRUG_CLASS = str_remove(DRUG_CLASS, " \\[Note \\d+\\]")) |>
    # reordering columns
    relocate(time, .before = total_CLASS) |>
    # creating column to differentiate data
    mutate(dataset = "ESPAUR 2024")
head(espaur_data)

tidying micro_cf_BLOOD data¶

In [ ]:
to_bind <-
micro_cf_BLOOD |>
  # filtering for bugs of interest
  filter(ORGANISM_OR_BUG=="Escherichia coli" |
           ORGANISM_OR_BUG=="Klebsiella pneumoniae") |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # removing additional drugs not mentioned in ESPAUR
  filter(!DRUG %in% c("AMOXYCILLIN","COTRIMOXAZOLE","TEMOCILLIN")) |>
  # selecting columns of interest
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         DRUG,
         DECODED) |>
  # creating time interval column
  mutate(
    # uncomment depending on time interval selection: name must match espaur data
    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "year"),
    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "quarter"),
    # reclassiyfing drugs per ESPAUR report
    DRUG_CLASS = case_when(
        # carbapenems
        DRUG %in% c("ERTAPENEM","IMIPENEM","MEROPENEM") ~ "Carbapenems",
        # third generation cephalosporins
        DRUG %in% c("CEFOTAXIME", "CEFTAZIDIME", "CEFPODOXIME","CEFTRIAXONE") ~ "Third Generation Cephalosporins",
        TRUE ~ str_to_title(DRUG))
        ) |>
  # counting total bugs-drug combinations per time interval by drug
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG) |>
  # creating total count column
  mutate(
         total_DRUG=n()
         ) |>
  ungroup() |>
  # counting total bugs-drug combinations per time interval by drug class (ESPAUR report)
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG_CLASS) |>
  # creating total timely count column
  mutate(
        total_CLASS=n()
        ) |>
  ungroup() |>
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG_CLASS) |>
  summarise(DECODED,
            total_CLASS,
            resistant_CLASS = sum(DECODED == "Resistant" |
                                  DECODED == "Intermediate", na.rm = TRUE)) |>
  select(-DECODED) |>
  relocate(
          time, .before = total_CLASS
          ) |>
  distinct() |>
  # creating column to differentiate data
  mutate(dataset = "iCARE")

visually checking data align¶

In [ ]:
head(espaur_data)
head(to_bind)

binding both datasets¶

In [ ]:
espaur_data <- rbind(espaur_data,to_bind)

# creating nonsusceptible column
espaur_data <- espaur_data |>
        mutate(nonsusceptible=(resistant_CLASS/total_CLASS)*100) |>
  # selecting data for years with bug-drug combinations > 5
  filter(total_CLASS>5)

kable(espaur_data)

plotting E. coli and K. pneumoniae yearly resistance rates selected drugs: micro_cf_BLOOD vs espaur data¶

14. line chart¶

In [ ]:
espaur_data |>
  # reordering factors
  mutate(dataset = factor(dataset, levels = c("iCARE","ESPAUR 2024"))) |>
  # ensuring drug names fit on y axi
  mutate(DRUG_CLASS = if_else(DRUG_CLASS == "Third Generation Cephalosporins", "Third Generation\nCephalosporins", DRUG_CLASS)) |>
  # plotting
  ggplot(aes(x=time,
             y=nonsusceptible,
             colour=ORGANISM_OR_BUG,
             shape=dataset
             )) +
  #geom_point(aes(size=total_CLASS),
             #alpha=0.8) +
  geom_line(aes(linetype = dataset),alpha=0.8) +
  labs(x = "Date",
       y = "Resistance (%)",
       colour = "Organism",
       linetype = "Data",
       shape="Dataset",
       size = "Isolate Count") +
  guides(colour="none") +
  theme_bw() +
  theme(  axis.title.x = element_text(vjust = -2),
          axis.title.y = element_text(vjust = 2),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.text.x = element_text(face = "italic"),
          strip.background = element_blank()
       ) +
  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG) +
  scale_colour_manual(values = c("#008080","#FFA500")) +
  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,"%")) +
  # enforcing ylim
  #guides(colour = guide_legend(order = 1)) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) #+
  # second national lockdown date
  #geom_vline(xintercept=as.Date("2020-11-05"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8) +
  # third national lockdown date
  #geom_vline(xintercept=as.Date("2021-01-06"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/14_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_yearly.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/14_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_quarterly.jpeg",
       #height= 8,
       #width=30)
     
png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       width=8.27,
       height=11.69,
       units="in",
       res=300
)
print(last_plot())
dev.off()

joining ukhsa data with bld_data data¶

tidying ukhsa data¶

In [ ]:
#kable(ukhsa_data)
ukhsa_data <-
ukhsa_data |>
    # selecting columns of interest as they relate to the micro_cf_BLOOD data
    select(ORGANISM_OR_BUG=Organism, 
           DRUG_CLASS=Antibiotic,
           status=Source,
           total_CLASS=Tested,
           nonsusceptible=`Resistant....`
           ) |>
    # renaming factor levels
    mutate(status = fct_recode(status, 
                               "Hospital Onset"="HA",
                               "Community Onset"="CA")) |>
    mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG == "E. coli","Escherichia coli","Klebsiella pneumoniae")) |>
    # reclassifying columns
    mutate(ORGANISM_OR_BUG = as.factor(ORGANISM_OR_BUG),
           DRUG_CLASS = as.factor(str_to_title(DRUG_CLASS))) |>
    # changing pip-taz to TAZOCIN & 3rd gen cephalosporions
    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,"Piperacillin-Tazobactam", "Tazocin")) |>
    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,"3rd Gen Cephalosporins", "Third Generation Cephalosporins")) |>
    # creating time column
    slice(rep(1:n(), each = 3)) |>
    mutate(time = rep(as.Date(c("2020-04-01","2021-03-15","2022-03-01")), times = n()/3)) |>
    # halving total for each tested count (across two timepoints) - just so it looks better visually
    mutate(total_CLASS = total_CLASS / 2) |>
    # creating column to differentiate data
    mutate(dataset = "UKHSA 2025") |>
    # reordering columns
    relocate(time, .before = status)
#kable(ukhsa_data)

tidying bld_data¶

In [ ]:
to_bind <-
bld_data |>
  # filtering for bugs of interest
  filter(ORGANISM_OR_BUG=="Escherichia coli" |
           ORGANISM_OR_BUG=="Klebsiella pneumoniae") |>
  # filtering for drugs of interest & those mentioned in UKHSA report
  filter(DRUG %in% drugs_of_interest) |>
  # renaming factor levels
  mutate(status = if_else(str_detect(AFTER_48HRS,"after"), "Hospital Onset", "Community Onset")) |>
  # selecting columns of interest
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         status,
         DRUG,
         DECODED) |>
  # creating time interval column
  mutate(
    # uncomment depending on time interval selection: name must match espaur data
    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "year"),
    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "quarter"),
    # reclassiyfing drugs per UKHSA report
    DRUG_CLASS = case_when(
        # aminoglycosides
        DRUG %in% c("AMIKACIN", "GENTAMICIN", "TOBRAMYCIN","NEOMYCIN","SPECTINOMYCIN","STREPTOMYCIN","KANAMYCIN") ~ "Aminoglycosides",
        # carbapenems
        DRUG %in% c("ERTAPENEM","IMIPENEM","MEROPENEM") ~ "Carbapenems",
        # third generation cephalosporins
        DRUG %in% c("CEFOTAXIME", "CEFTAZIDIME") ~ "Third Generation Cephalosporins",
        TRUE ~ str_to_title(DRUG))
        ) |>
  # counting total bugs-drug combinations per time interval by drug
  group_by(ORGANISM_OR_BUG,
           status,
           time,
           DRUG) |>
  # creating total count column
  mutate(
         total_DRUG=n()
         ) |>
  ungroup() |>
  # counting total bugs-drug combinations per time interval by drug class (UKHSA report)
  group_by(ORGANISM_OR_BUG,
           status,
           time,
           DRUG_CLASS) |>
  # creating total timely count column
  mutate(
        total_CLASS=n()
        ) |>
  ungroup() |>
  group_by(ORGANISM_OR_BUG,
           status,
           time,
           DRUG_CLASS) |>
  summarise(DECODED,
            total_CLASS,
            resistant_CLASS = sum(DECODED == "Resistant" |
                                  DECODED == "Intermediate", na.rm = TRUE)) |>
  ungroup() |>
  select(-DECODED) |>
  relocate(
          time, .before = total_CLASS
          ) |>
  distinct() |>
  # calculating percentage
  mutate(nonsusceptible = (resistant_CLASS/total_CLASS)*100) |>
  # creating column to differentiate data
  mutate(dataset = "iCARE") |>
        select(ORGANISM_OR_BUG,
               DRUG_CLASS,
               status,
               total_CLASS,
               nonsusceptible,
               time,
               dataset)

visually checking data align¶

In [ ]:
kable(ukhsa_data)
kable(to_bind)

binding both datasets¶

In [ ]:
ukhsa_data <- rbind(ukhsa_data,to_bind)
#kable(ukhsa_data)

plotting K. pneumoniae yearly resistance rates selected drugs: bld_data vs ukhsa data¶

15. line chart¶

HO vs CO, Kpn only¶

In [ ]:
# line chart
ukhsa_data |>
  # filtering for bug of interest
  #filter(
        #ORGANISM_OR_BUG=="Escherichia coli" #|
        #ORGANISM_OR_BUG=="Klebsiella pneumoniae"
        #) |>
  # filtering out total count
  filter(status != "Total") |>
  # filtering for drugs of interest (defined by UKHSA)
  filter(DRUG_CLASS %in% c("Co-Amoxiclav", "Aminoglycosides", "Ciprofloxacin", "Carbapenems", "Tazocin", "Third Generation Cephalosporins")) |>
  # ensuring drug names fit on y axi
  mutate(DRUG_CLASS = if_else(DRUG_CLASS == "Third Generation Cephalosporins", "Third Generation\nCephalosporins", DRUG_CLASS)) |>
  # plotting
  ggplot(aes(x=time,
             y=nonsusceptible,
             colour=status,
             #shape=dataset
             )) +
  #geom_point(aes(size=total_CLASS),
             #alpha=0.8) +
  geom_line(aes(linetype = dataset),alpha=0.8) +
  scale_linetype_manual(values = c("solid", "dotdash")) +
  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,"%")) +
  labs(x = "Date",
       y = "Resistance (%)",
       colour = "Infection Category",
       linetype = "Data",
       shape="Dataset",
       size = "Isolate Count") +
  #guides(linetype="none") +
  theme_bw() +
  theme(  axis.title.x = element_text(vjust = -2),
          axis.title.y = element_text(vjust = 2),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.text.x = element_text(face = "italic"),
          strip.background = element_blank()
       ) +
  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/15_bld_data_resistance_Kpn_ONLY_UKHSA_quarterly.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/15_bld_data_resistance_Ec_ONLY_UKHSA_quarterly.jpeg",
       #height= 8,
       #width=20)

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       width=8.27,
       height=10.02,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting K. pneumoniae yearly resistance rates selected drugs: micro_cf_BLOOD vs espaur data vs ukhsa data¶

tidying data¶

micro_cf_BLOOD¶

In [ ]:
to_bind <-
micro_cf_BLOOD |>
  # filtering for bugs of interest
  filter(ORGANISM_OR_BUG=="Escherichia coli" |
           ORGANISM_OR_BUG=="Klebsiella pneumoniae") |>
  # filtering for drugs of interest (defined in 4. GLMM)
  filter(DRUG %in% drugs_of_interest) |>
  # removing additional drugs not mentioned in ESPAUR
  filter(!DRUG %in% c("AMOXYCILLIN","COTRIMOXAZOLE","TEMOCILLIN")) |>
  # selecting columns of interest
  select(SUBJECT,
         SAMPLE_COLLECTED_DT,
         ORGANISM_OR_BUG,
         DRUG,
         DECODED) |>
  # creating time interval column
  mutate(
    # uncomment depending on time interval selection: name must match espaur data
    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "year"),
    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, "quarter"),
    # reclassiyfing drugs per ESPAUR report & UKHSA report
    DRUG_CLASS = case_when(
        # aminoglycosides
        DRUG %in% c("AMIKACIN", "GENTAMICIN", "TOBRAMYCIN","NEOMYCIN","SPECTINOMYCIN","STREPTOMYCIN","KANAMYCIN") ~ "Aminoglycosides",
        # carbapenems
        DRUG %in% c("ERTAPENEM","IMIPENEM","MEROPENEM") ~ "Carbapenems",
        # third generation cephalosporins
        DRUG %in% c("CEFOTAXIME", "CEFTAZIDIME", "CEFPODOXIME","CEFTRIAXONE") ~ "Third Generation Cephalosporins",
        TRUE ~ str_to_title(DRUG))
        ) |>
  # counting total bugs-drug combinations per time interval by drug
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG) |>
  # creating total count column
  mutate(
         total_DRUG=n()
         ) |>
  ungroup() |>
  # counting total bugs-drug combinations per time interval by drug class (ESPAUR report)
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG_CLASS) |>
  # creating total timely count column
  mutate(
        total_CLASS=n()
        ) |>
  ungroup() |>
  group_by(ORGANISM_OR_BUG,
           time,
           DRUG_CLASS) |>
  summarise(DECODED,
            total_CLASS,
            resistant_CLASS = sum(DECODED == "Resistant" |
                                  DECODED == "Intermediate", na.rm = TRUE)) |>
  select(-DECODED) |>
  relocate(
          time, .before = total_CLASS
          ) |>
  distinct() |>
  # creating column to differentiate data
  mutate(dataset = "iCARE") |>
  mutate(nonsusceptible = (resistant_CLASS/total_CLASS)*100) |>
  select(-resistant_CLASS) |>
  relocate(nonsusceptible, .before = dataset)

ukhsa and espaur data¶

In [ ]:
all_national <- ukhsa_data |>
                 filter(status == "Total") |>
                 select(-status)

espaur_data <- espaur_data |>
            select(-c(resistant_CLASS)) |>
            relocate(dataset, .after = nonsusceptible)

visually checking data align¶

In [ ]:
kable(to_bind)
kable(all_national)
kable(espaur_data)

binding datasets¶

In [ ]:
all_national <- rbind(all_national,to_bind)
all_national <- rbind(all_national, espaur_data)

#kable(all_national)
In [ ]:
all_national |>
group_by(dataset) |>
tally()

plotting¶

16. line chart¶

In [ ]:
all_national |>
  # filtering for bug of interest
  #filter(
        #ORGANISM_OR_BUG=="Escherichia coli" #|
        #ORGANISM_OR_BUG=="Klebsiella pneumoniae"
        #) |>
  # ordering
  mutate(dataset = factor(dataset, levels = c("iCARE","ESPAUR 2024", "UKHSA 2025"))) |>
  # ensuring drug names fit on y axi
  mutate(DRUG_CLASS = if_else(DRUG_CLASS == "Third Generation Cephalosporins", "Third Generation\nCephalosporins", DRUG_CLASS)) |>
  # plotting
  ggplot(aes(x=time,
             y=nonsusceptible,
             colour=ORGANISM_OR_BUG,
             shape=dataset
             )) +
  #geom_point(aes(size=total_CLASS),
             #alpha=0.8) +
  geom_line(aes(linetype = dataset),alpha=0.8) +
  labs(x = "Date",
       y = "Resistance (%)",
       #colour = "Dataset",
       linetype = "Data",
       #size = "Isolate Count"
       ) +
  scale_linetype_manual(values = c("solid","dashed","dotdash")) +
  guides(colour="none")+
  theme_bw() +
  theme(  axis.title.x = element_text(vjust = -2),
          axis.title.y = element_text(vjust = 2),
          # add legend box
          legend.background=element_blank(),
          legend.box.background=element_rect(colour = "black"),
          # ensuring even legend border
          legend.margin=margin(4,4,4,4, unit = "mm"),
          # strips
          strip.text = element_text(size=11),
          strip.text.x = element_text(face = "italic"),
          strip.background = element_blank()
       ) +
  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG) +
  #scale_colour_igv() +
  scale_colour_manual(values = c("#008080","#FFA500")) +
  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,"%")) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             alpha=0.8) #+
  # second national lockdown date
  #geom_vline(xintercept=as.Date("2020-11-05"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8) +
  # third national lockdown date
  #geom_vline(xintercept=as.Date("2021-01-06"),
             #linetype = "dashed",
             #color = "grey",
             #alpha=0.8)

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_UKHSA_yearly.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Kpn_ONLY_ESPAUR_UKHSA_yearly.jpeg",
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Ec_ONLY_ESPAUR_UKHSA_yearly.jpeg",
       #height= 7,
       #width=30)

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       width=8.27,
       height=11.69,
       units="in",
       res=300
)
print(last_plot())
dev.off()

<<< 7. INVESTIGATING MULTI-DRUG RESISTANCE >>>¶

creating upset data¶

In [ ]:
upset <-
#micro_cf_ALL |>
micro_cf_BLOOD |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
    select(SUBJECT,
           SAMPLE_COLLECTED_DT,
           ORGANISM_OR_BUG,
           DRUG,
           DRUG_CLASS,
           DECODED) |>
    mutate(DECODED_2 = DECODED %in% c("Resistant","Intermediate")) |>
    select(-c(DECODED,DRUG_CLASS)) |>
    filter(DRUG %in% drugs_of_interest) |>
    distinct() |>
    #group_by(SUBJECT,SAMPLE_COLLECTED_DT,ORGANISM_OR_BUG)|>
    pivot_wider(names_from = DRUG,
                values_from = DECODED_2,
                values_fn = list(DECODED_2 = any),
                values_fill = list(DECODED_2 = FALSE)) |>
                # converting to 1,0 binary
    mutate(across(`CO-AMOXICLAV`:GENTAMICIN, ~as.integer(.)))

colnames(upset)[4:15] <- str_to_title(colnames(upset)[4:15])

upset

filtering for MDR profiles only¶

BE AWARE OF THIS IN DOWNSTREAM ANALYSES¶

In [ ]:
# converting binary to logical
upset <-
upset |>
    mutate(across(`Co-Amoxiclav`:Gentamicin, ~as.logical(.))) |>
    # filtering singular resistances and empty rows
    filter(rowSums(across(`Co-Amoxiclav`:Gentamicin, ~ .)) > 1)

plotting MDR upset data across all organisms¶

In [ ]:
# ordering sets
sets_ordered <- c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )

# ordering columns
upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]

sets <- as.character(colnames(upset)[4:15])

# focussing on exclusive interactions
presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
       aggregate(
              as.formula(paste0(presence, "~ intersection")),
              df,
              FUN=sum
       )
}

# plotting data across all organisms
ComplexUpset:::upset(as.data.frame(upset),
      sets,
      sort_sets = FALSE,
      stripes="white",
      name = "\n Phenotypic Resistance Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=50,
      base_annotations=list(
       "Count"=(
              ggplot() +
              geom_bar(data=summarise_values,
                       stat="identity",
                       aes(y=!!presence),
                       alpha=0.8,
                       fill="#008080") +
                       ylab("Isolate Count"))),
      annotations=list(
       "Organism"=(
              ggplot(mapping=aes(fill=as.factor(ORGANISM_OR_BUG))) +
              geom_bar(stat="count",position="fill",alpha=0.8) +
              scale_y_continuous(labels=function(x) paste0(x*100,"%")) +
              scale_fill_manual(values = c("#008080","#FFA500","#708090")) +
              labs(y="Proportion (%)", fill = "Organism") +
              theme(axis.title.y=element_text(vjust=1),
                    legend.text = element_text(size=11,face = "italic"))
              )),
      set_sizes=(upset_set_size(
       geom=geom_bar(width=0.8, aes(y=..count..),
                                    alpha=0.8)) +
       ylab("\nIsolate Count")),
      queries = list(
       upset_query(set="Amikacin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Gentamicin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Ertapenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Meropenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Ceftazidime", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ceftriaxone", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ciprofloxacin", fill="#631879CC", color_by="fill"),
       upset_query(set="Amoxycillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Co-Amoxiclav", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Tazocin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Temocillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Cotrimoxazole", fill="#A20056CC", color_by="fill")
      )
      )

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #height= 8,
       #width=20)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_all.jpeg",
       height=8.27,
       width=11.69,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting MDR upset data for individual organisms¶

In [ ]:
# ordering sets
sets_ordered <- c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )

# ordering columns
upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]

sets <- as.character(colnames(upset)[4:15])

# focussing on exclusive interactions
presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
       aggregate(
              as.formula(paste0(presence, "~ intersection")),
              df,
              FUN=sum
       )
}

# plotting data across all organisms
ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG==#"Klebsiella pneumoniae",
                                                              #"Escherichia coli",
                                                              "Other Enterobacteriaceae",
                    ]),
      sets,
      sort_sets = FALSE,
      stripes="white",
      name = "\n Phenotypic Resistance Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=10,
      #min_size=25,
      base_annotations=list(
       "Count"=(
              ggplot() +
              geom_bar(data=summarise_values,
                       stat="identity",
                       aes(y=!!presence),
                       alpha=0.8,
                       fill=#"#FFA500" # Kpn
                            #"#008080" # Ec
                            "#708090" # Other Eb
                     ) +
                       ylab("Isolate Count"))),
      set_sizes=(upset_set_size(
       geom=geom_bar(width=0.8, aes(y=..count..),
                                    alpha=0.8)) +
       ylab("\nIsolate Count")),
      queries = list(
       upset_query(set="Amikacin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Gentamicin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Ertapenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Meropenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Ceftazidime", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ceftriaxone", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ciprofloxacin", fill="#631879CC", color_by="fill"),
       upset_query(set="Amoxycillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Co-Amoxiclav", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Tazocin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Temocillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Cotrimoxazole", fill="#A20056CC", color_by="fill")
      )
      )

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #height= 8,
       #width=20)

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_kpn.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_ec.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_oe.jpeg",
       height=8.27,
       width=11.69,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting MDR profiles across time¶

working out top 5 Kpn MDR profiles¶

In [ ]:
# plotting data across all organisms
ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG=="Klebsiella pneumoniae",
                                                              #"Escherichia coli",
                                                              #"Other Enterobacteriaceae",
                    ]),
      sets,
      sort_sets = FALSE,
      stripes="white",
      name = "\n Phenotypic Resistance Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=45,
      base_annotations=list(
       "Count"=(
              ggplot() +
              geom_bar(data=summarise_values,
                       stat="identity",
                       aes(y=!!presence),
                       alpha=0.8,
                       fill="#FFA500" # Kpn
                            #"#008080" # Ec
                            #"#708090" # Other Eb
                     ) +
                       ylab("Number of Isolates"))),
      set_sizes=(upset_set_size(
       geom=geom_bar(width=0.8, aes(y=..count..),
                                    alpha=0.8)) +
       ylab("\nNumber of Isolates")),
      queries = list(
       upset_query(set="Amikacin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Gentamicin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Ertapenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Meropenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Ceftazidime", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ceftriaxone", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ciprofloxacin", fill="#631879CC", color_by="fill"),
       upset_query(set="Amoxycillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Co-Amoxiclav", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Tazocin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Temocillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Cotrimoxazole", fill="#A20056CC", color_by="fill")
      )
      )

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       height=8.27,
       width=11.69,
       units="in",
       res=300
)
print(last_plot())
dev.off()

Kpn top MDR profiles¶

1. Gentamicin (Aminoglycosides) - Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Co-Amoxiclav & Tazocin (Penicillins) & Cotrimoxazole (Sulfonamides)¶

2. Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Co-Amoxiclav & Tazocin (Penicillins) & Cotrimoxazole (Sulfonamides)¶

3. Ertapenem (Carbapenems) - Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Temocillin (Penicillins)¶

4. All drugs¶

5. Ceftazidime & Ceftriaxone (Cephalosporins) - Amoxycillin & Co-Amoxiclav (Penicillins) - Cotrimoxazole (Sulfonamides)¶

In [ ]:
upset |>
    rowwise()|>
    mutate(MDR = case_when(
         Amikacin & Gentamicin & Ertapenem & Meropenem & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Temocillin & Cotrimoxazole ~ "PDR", # largest group must be first per case_when()
         Gentamicin & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Cotrimoxazole ~ "MDR 1",
         Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Cotrimoxazole ~ "MDR 2",
         Ertapenem & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & Temocillin ~ "MDR 3",
         Ceftazidime & Ceftriaxone & Amoxycillin & `Co-Amoxiclav` & Cotrimoxazole ~ "MDR 4",
         TRUE ~ NA_character_
    )) |>
  ungroup() |>
  # filtering for Kpn
  filter(ORGANISM_OR_BUG == "Klebsiella pneumoniae") |>
  # filtering NAs
  filter(!is.na(MDR)) |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "quarter")) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    MDR,
    MONTH
  ) |>
  tally() |>
ggplot(aes(x=MONTH,
           y=n,
           colour=MDR)) +
  geom_line(alpha=0.8) +
  # first national lockdown date
  geom_vline(xintercept=as.Date("2020-03-23"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # second national lockdown date
  geom_vline(xintercept=as.Date("2020-11-05"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  # third national lockdown date
  geom_vline(xintercept=as.Date("2021-01-06"),
             linetype = "dashed",
             color = "grey",
             size=0.3,
             alpha=0.8) +
  labs(x = "Date",
       y = "Isolate Count",
       colour = "Multi-Drug Resistance Profile") +
  theme_bw() +
  scale_colour_bmj() +
  # sizing
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(),
        # legend text
        legend.text = element_text(size=11), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.title = element_text(size=11))

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/Kpn_quarterly_MDR_profiles.jpeg",
       height=3,
       width=8,
       units="in",
       res=300
)
print(last_plot())
dev.off()

investigating co-occurrence of resistance phenotypes¶

In [ ]:
cooccurrence <-upset  |>
    # converting to 1,0 binary
    mutate(across(`Co-Amoxiclav`:Gentamicin, ~as.integer(.))) |>
    select(`Co-Amoxiclav`:Gentamicin) |>
    as.matrix() #|>
    #crossprod()

cooccurrence

corrplot::corrplot(cor(cooccurrence), method = "square")

investigating multi-level associations¶

In [ ]:
mca <-
upset |>
    select(ORGANISM_OR_BUG,`Co-Amoxiclav`:Gentamicin) |>
    mutate(across(-ORGANISM_OR_BUG, as.factor)) #|>
    # filtering by bug
    #filter(ORGANISM_OR_BUG == "Klebsiella pneumoniae")

# mca results FactoMineR
mca_results <- MCA(mca, graph = FALSE, 
        # comment-out below if bug specific
        quali.sup=1
        )

true_vars <- grep("_TRUE$", rownames(mca_results$var$coord), value = TRUE)
In [ ]:
mca
In [ ]:
mca_results$eig[1:5, ]
In [ ]:
fviz_mca_var(mca_results, 
             select.var = list(name = true_vars),
             repel = TRUE,
             col.var = "contrib")

png(
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg",
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/All_MCA_plot.jpeg",
       #filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/Kpn_MCA_plot.jpeg",
       height=8,
       width=6,
       units="in",
       res=300
)
print(last_plot())
dev.off()

plotting upset data for Kpn blood isolates, April 2020 - December 2021¶

In [ ]:
upset <- upset |>
  # filtering for April 2020 - December 2021
  filter(SAMPLE_COLLECTED_DT >= as.Date("2020-04-01") & SAMPLE_COLLECTED_DT <= as.Date("2021-12-31"))

# ordering sets
sets_ordered <- c(
       "Amikacin",
       "Gentamicin",
       "Ertapenem",
       "Meropenem",
       "Ceftazidime",
       "Ceftriaxone",
       "Ciprofloxacin",
       "Amoxycillin",
       "Co-Amoxiclav",
       "Tazocin",
       "Temocillin",
       "Cotrimoxazole"
  )

# ordering columns
upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]

sets <- as.character(colnames(upset)[4:15])

# focussing on exclusive interactions
presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
       aggregate(
              as.formula(paste0(presence, "~ intersection")),
              df,
              FUN=sum
       )
}

# plotting data across all organisms
ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG=="Klebsiella pneumoniae",]),
      sets,
      sort_sets = FALSE,
      stripes="white",
      name = "\n Phenotypic Resistance Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=5,
      base_annotations=list(
       "Count"=(
              ggplot() +
              geom_bar(data=summarise_values,
                       stat="identity",
                       aes(y=!!presence),
                       alpha=0.8,
                       fill="#FFA500" # Kpn
                            #"#008080" # Ec
                            #"#708090" # Other Eb
                     ) +
                       ylab("Number of Isolates"))),
      set_sizes=(upset_set_size(
       geom=geom_bar(width=0.8, aes(y=..count..),
                                    alpha=0.8)) +
       ylab("\nNumber of Isolates")),
      queries = list(
       upset_query(set="Amikacin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Gentamicin", fill="#3B4992CC", color_by="fill"),
       upset_query(set="Ertapenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Meropenem", fill="#EE0000CC", color_by="fill"),
       upset_query(set="Ceftazidime", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ceftriaxone", fill="#008B45CC", color_by="fill"),
       upset_query(set="Ciprofloxacin", fill="#631879CC", color_by="fill"),
       upset_query(set="Amoxycillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Co-Amoxiclav", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Tazocin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Temocillin", fill="#5F559BCC", color_by="fill"),
       upset_query(set="Cotrimoxazole", fill="#A20056CC", color_by="fill")
      )
      )

#ggsave(plot=last_plot(),
       #"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       #height= 8,
       #width=20)

png(
       filename="/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg",
       height=5,
       width=10,
       units="in",
       res=300
)
print(last_plot())
dev.off()

<<< 8. DATA TABLES >>>¶

overall summary tables¶

demographics¶

In [ ]:
table <-
all_data |>
#bld_data  |>
# filtering for bugs of interest
filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
    select(SUBJECT,
           AGE_AT_ADMISSION,
           sex=GENDER_DESC,
           ETHNICITY_DESC) |>
    mutate(sex = str_to_title(sex),
           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>
    distinct() |>
    mutate(
           age_band = cut(
            AGE_AT_ADMISSION,
            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),
            lables = c("leq1", "2-5", " 6-9", "10-17", "18-25", "26-20","41-65", "65-80", "80+"),
            right=TRUE
           )
    ) |>
    filter(!is.na(age_band)) |>
    count(age_band, sex) |>
    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>
    mutate(
        M_pct = round(Male/sum(Male)*100, 1),
        F_pct = round(Female/sum(Female)*100, 1),
        Total = Male+Female,
        Total_pct = round(Total/sum(Total)*100, 1)
    )

bind_rows(table, 
            table |>
            summarise(across(-age_band, sum)) |>
            mutate(age_band = "Overall")) |>
            kable(align="lrrrrrr")
In [ ]:
all_data |>
#bld_data  |>
# filtering for bugs of interest
filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  mutate(
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
    select(SUBJECT,
           HO,
           AGE_AT_ADMISSION,
           sex=GENDER_DESC,
           ETHNICITY_DESC) |>
    mutate(sex = str_to_title(sex),
           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>
    distinct() |>
    mutate(
           age_band = cut(
            AGE_AT_ADMISSION,
            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),
            lables = c("leq1", "2-5", " 6-9", "10-17", "18-25", "26-20","41-65", "65-80", "80+"),
            right=TRUE
           )
    ) |>
    #filter(!is.na(age_band)) |>
    count(HO, age_band, sex) |>
    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>
    mutate(
        M_pct = round(Male/sum(Male)*100, 1),
        F_pct = round(Female/sum(Female)*100, 1),
        Total = Male+Female,
        Total_pct = round(Total/sum(Total)*100, 1)
    ) |>
    mutate(sum_male = sum(Male),
           sum_female = sum(Female))
In [ ]:
all_data |>
#bld_data  |>
filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
    select(SUBJECT,
           AGE_AT_ADMISSION,
           sex=GENDER_DESC,
           HO
           ETHNICITY_DESC) |>
    mutate(sex = str_to_title(sex),
           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>
    distinct() |>
    group_by(sex) |>
    summarise(
        mean=mean(AGE_AT_ADMISSION, na.rm = T),
        median=median(AGE_AT_ADMISSION, na.rm = T),
        range=range(AGE_AT_ADMISSION, na.rm = T)
    )

bugs¶

In [ ]:
#micro_cf_ALL |>
micro_cf_BLOOD |>
filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
    select(SUBJECT,
           SAMPLE_COLLECTED_DT,
           ORGANISM_OR_BUG) |>
    distinct() |>
    group_by(
        ORGANISM_OR_BUG,
        ) |>
    tally()
In [ ]:
#micro_cf_ALL |>
#micro_cf_BLOOD |>
#all_data |>
bld_data |>
# defining hospital onset infections
  mutate(
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
    select(SUBJECT,
           SPELL_IDENTIFIER,
           EPISODE_IDENTIFIER,
           SAMPLE_COLLECTED_DT,
           HO,
           ORGANISM_OR_BUG) |>
    distinct() |>
    group_by(
        ORGANISM_OR_BUG,
        HO
        ) |>
    tally()

sustained spike in Kpn blood isolates from HO infections during the pandemic 01/2021-02/2021 - age/gender¶

spike in Klebsiella spp from HO infections during the same months - age/gender¶

In [ ]:
bld_data  |>
  # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # grouping other Enterobacteriaceae in "Other" category
  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c("Escherichia coli","Klebsiella pneumoniae"), 
         ORGANISM_OR_BUG, "Other Enterobacteriaceae")) |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
  # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    HO,
    SUBJECT,
    MONTH
  ) |>
  tally() |>
  arrange(desc(n)) |>
  filter(ORGANISM_OR_BUG=="Klebsiella pneumoniae",HO=="Hospital Onset",MONTH >= "2021-01-01",MONTH <= "2021-02-28")
In [ ]:
bld_data |>
    # filtering for HO infections & bug of interest
    filter(!ORGANISM_OR_BUG %in% c("Klebsiella pneumoniae","Escherichia coli", "Other, including Gram +ves"), AFTER_48HRS == "Collection after 48 hours of admission") |>
    select(SUBJECT,SPELL_IDENTIFIER, EPISODE_IDENTIFIER, OLD_BUGS, SAMPLE_COLLECTED_DT) |>
    distinct() |>
    #filter(SAMPLE_COLLECTED_DT >= "2021-01-01" & SAMPLE_COLLECTED_DT <= "2021-04-30") |> # Other Enterobacteriaceae spike jan-april 2021
    filter(SAMPLE_COLLECTED_DT >= "2020-04-01" & SAMPLE_COLLECTED_DT <= "2020-04-30") |> # Other Enterobacteriaceae spike april 2020
    group_by(OLD_BUGS) |>
    tally()
In [ ]:
table <-
#all_data |>
bld_data |>
    # filtering for HO infections & bug of interest
    filter(ORGANISM_OR_BUG=="Escherichia coli", AFTER_48HRS == "Collection after 48 hours of admission") |>
    #filter(ORGANISM_OR_BUG=="Klebsiella pneumoniae", AFTER_48HRS == "Collection after 48 hours of admission") |>
    # filtering for dates of interest
    mutate(SAMPLE_COLLECTED_DT = as.Date(SAMPLE_COLLECTED_DT, format = "%Y-%m-%d")) |>
    #filter(SAMPLE_COLLECTED_DT >= "2020-04-01" & SAMPLE_COLLECTED_DT <= "2020-04-30") |> # Ec spike april 2020
    filter(SAMPLE_COLLECTED_DT >= "2021-02-01" & SAMPLE_COLLECTED_DT <= "2021-02-28") |> # Ec spike feb 2021
    #filter(SAMPLE_COLLECTED_DT >= "2021-01-01" & SAMPLE_COLLECTED_DT <= "2021-02-28") |> # Kpn spike jan-feb 2021
    select(SUBJECT,
           AGE_AT_ADMISSION,
           sex=GENDER_DESC,
           ETHNICITY_DESC) |>
    mutate(sex = str_to_title(sex),
           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>
    distinct() |>
    mutate(
           age_band = cut(
            AGE_AT_ADMISSION,
            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),
            lables = c("leq1", "2-5", " 6-9", "10-17", "18-25", "26-20","41-65", "65-80", "80+"),
            right=TRUE
           )
    ) |>
    count(age_band, sex) |>
    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>
    mutate(
        M_pct = round(Male/sum(Male)*100, 1),
        F_pct = round(Female/sum(Female)*100, 1),
        Total = Male+Female,
        Total_pct = round(Total/sum(Total)*100, 1)
    )

bind_rows(table, 
            table |>
            summarise(across(-age_band, sum)) |>
            mutate(age_band = "Overall")) |>
            kable(align="lrrrrrr")

what accounts for the greater difference between HO versus CO isolates in Kpn & Other Enterobacteriaceae for all isolates compared to blood isolates only? culture type/bacteria¶

looks like Enterobacter spp. are primarily responsible¶

In [ ]:
micro_cf |>
    # filtering for blood cultures only
    filter(str_detect(ORDER_NAME,
                      "urine"
                      #"sputum"
                      ),
           str_detect(SENSITIVITY,
                      "enterobacter"
                      #"klebsiella pneumoniae"
                      )
           ) |>
    group_by(SENSITIVITY) |>
    tally() |>
    arrange(desc(n)) |>
    kable()
In [ ]:
all_data |>
 # filtering non-Enterobacteriaceae
  filter(ORGANISM_OR_BUG != "Other, including Gram +ves") |>
  # selecting columns of interest
  select(SUBJECT,
         SPELL_IDENTIFIER,
         EPISODE_IDENTIFIER,
         SAMPLE_COLLECTED_DT,
         WITHIN_SPELL,
         AFTER_48HRS,
         ORGANISM_OR_BUG) |>
  # removing duplicates
  distinct() |>
  # creating month column
  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, "month"),
         # defining hospital onset infections
         HO=if_else(
           !is.na(WITHIN_SPELL) &
             WITHIN_SPELL == TRUE &
             !is.na(AFTER_48HRS) &
             AFTER_48HRS == "Collection after 48 hours of admission", "Hospital Onset", 
           # defining community onset infections
           if_else(
             !is.na(WITHIN_SPELL) &
               !is.na(AFTER_48HRS) &
               AFTER_48HRS == "Collection within 48 hours of admission", "Community Onset",
            # else
            "Undefined"))) |>
   # filtering incomplete end month
  filter(MONTH < end_date) |>
  # counting total bugs per month for each bug
  group_by(
    ORGANISM_OR_BUG,
    HO,
    MONTH
  ) |>
  tally()