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)
# 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)
# list all packages
#installed.packages()[,"Package"]
# find specific packages
"package::FactoMineR" %in% search()
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)
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
packageVersion("stats")
# 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")
micro_cf <- micro
demographics_cf <- demographics
episodes_cf <- episodes
micro_cf<-micro_cf |>
mutate(SAMPLE_COLLECTED_DT = lubridate::as_date(ymd_hms(SAMPLE_COLLECTED_DT)))
class(micro_cf$SAMPLE_COLLECTED_DT)
episodes_cf<-episodes_cf |>
mutate(across(c(ADMISSION_DATE, EPISODE_START_DATE, EPISODE_END_DATE, DISCHARGE_DATE), ymd))
class(episodes_cf$ADMISSION_DATE)
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))
# 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()
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)
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))
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))
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)
# microbiology data
mic_breakpoints <- read.csv("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/AB_guidelines.csv")
head(mic_breakpoints)
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))
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))
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",
))
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",
))
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)
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)
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)
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)
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)
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)
load("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/09052025.RData")
ls()
## BE CAREFUL NOT TO RUN THE BELOW WHEN INAPPROPRIATE
#save.image("/home/azureuser/cloudfiles/code/Users/jrodgus-icare/X.RData")
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)
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)
end_date <- as.Date("2025-04-01")
# 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()
# 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()
# 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)
# 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)
# 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()
# 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()
# 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()
# 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()
# 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()
# 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()
# 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()
# 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)
# 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()
# 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()
# 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()
#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`))
# 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")
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)
# 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")
interrupted_ts <- glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * (tp1 + tp2 + tp3) + (1|ORGANISM_OR_BUG:DRUG),
data = model_data,
family = "binomial")
options(na.action = "na.fail")
model_set <- dredge(interrupted_ts)
kable(model_set)
# 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)
summary(get.models(model_set, 1)[[1]])
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
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)
# 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")
kable(all_summaries)
# 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")
kable(all_summaries)
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)
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)
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)
# 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")
# 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)
summary(get.models(model_set, 1)[[1]])
# 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")
kable(all_summaries)
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)
# 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)
# 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)
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)
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")
head(espaur_data)
head(to_bind)
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)
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()
#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)
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)
kable(ukhsa_data)
kable(to_bind)
ukhsa_data <- rbind(ukhsa_data,to_bind)
#kable(ukhsa_data)
# 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()
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)
all_national <- ukhsa_data |>
filter(status == "Total") |>
select(-status)
espaur_data <- espaur_data |>
select(-c(resistant_CLASS)) |>
relocate(dataset, .after = nonsusceptible)
kable(to_bind)
kable(all_national)
kable(espaur_data)
all_national <- rbind(all_national,to_bind)
all_national <- rbind(all_national, espaur_data)
#kable(all_national)
all_national |>
group_by(dataset) |>
tally()
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()
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
# 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)
# 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()
# 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 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()
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()
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")
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)
mca
mca_results$eig[1:5, ]
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()
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()
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")
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))
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)
)
#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()
#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()
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")
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()
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")
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()
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()