-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData_analysis_SPINZ.Rmd
More file actions
1821 lines (1493 loc) · 78.5 KB
/
Data_analysis_SPINZ.Rmd
File metadata and controls
1821 lines (1493 loc) · 78.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "SPINZ genomic analysis"
author: "Laura T Phillips"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
prettydoc::html_pretty:
theme: cayman
toc: true
---
## Set working directory and load packages
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# set working directory to the location of the script
knitr::opts_knit$set(root.dir = getwd())
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# load packages
library(knitr)
library(tidyverse)
library(dplyr)
library(ggplot2)
library(ggrepel)
library(patchwork)
library(forcats)
library(ggtree)
library(ape)
library(readxl)
library(coda)
library(cowplot)
library(phytools)
library(lubridate)
library(waffle)
library(RColorBrewer)
library(dendextend)
library(janitor)
library(gtsummary)
library(rcompanion)
library(gtsummary)
library(ComplexUpset)
library(genoPlotR)
```
## Print session info (package versions)
```{r session_info}
# print versions
sessionInfo()
```
## Set colour palettes
```{r}
st_colours <- c('ST307' = '#a6cee3', 'ST2004' = '#fb9a99', 'ST983' = '#b2df8a','ST5856' = '#33a02c','ST101' = '#1f78b4' ,'ST985' = '#e31a1c', 'ST147' = '#fdbf6f','ST15' = '#ff7f00','ST1119' = '#cab2d6', 'Other' = '#fccde5')
born_loc <- c("Inborn" = "#d94701", "Unknown" = "#bdbdbd", "Outborn" = "#fdae6b")
clusters_cols <- c("1" = "#7fc97f", "2" = "#756bb1", "3" = "#fdc086", "4" = "#386cb0", "5" = "#f0027f", "6" = "#e41a1c", "Missing data" = "#999999", "NC" = "black")
res_colours <- c("Bla ESBL" = '#fa9fb5', "Aminoglycosides" = '#66c2a4', "Macrolides" = '#807dba', "Sulfonamide" = '#fc8d59', "Trimethoprim" = '#0570b0', "Yersiniabactin" = '#cccccc', 'NA' = 'white')
all_res_colours <- c("Bla ESBL" = '#fa9fb5', "Bla" = "#a6cee3", "Carbapenemase" = "#b2df8a", "Quinolone" = "#e31a1c", "Phenicol" = "#cab2d6", "Tetracycline" = "#ffff99", "Rifampicin" = "#b15928", "Aminoglycosides" = '#66c2a4', "Macrolides" = '#807dba', "Sulfonamide" = '#fc8d59', "Trimethoprim" = '#0570b0', "Yersiniabactin" = '#cccccc', 'NA' = 'white')
```
## Load data on included samples - Table S2
```{r}
kleb_clin <- read_tsv("tables/Supplementary_table_S2.tsv")
# Create ST grouped column
kleb_clin <- kleb_clin %>%
add_count(`Sequence type`, name="ST_count") %>%
mutate(`Sequence type category` = ifelse(ST_count >=4, `Sequence type`, ifelse(`Sequence type` == "ST307-1LV", "ST307", 'Other'))) %>%
mutate(days_to_onset_cat = case_when(
is.na(`Days to onset`) ~ "Unknown",
`Days to onset` < 0 ~ "Unknown",
`Days to onset` >= 8 ~ "8+ days",
TRUE ~ as.character(`Days to onset`))) %>%
mutate(onset_group = case_when(
days_to_onset_cat %in% c("0", "1", "2") ~ "Rapid",
days_to_onset_cat == "Unknown" ~ "Unknown",
TRUE ~ "Delayed"
)) %>%
select(-ST_count)
# Create onset category data - rapid and delayed onset
kleb_clin <- kleb_clin %>%
mutate(days_to_onset_cat = case_when(
is.na(`Days to onset`) ~ "Unknown",
`Days to onset` < 0 ~ "Unknown",
`Days to onset` >= 8 ~ "8+ days",
TRUE ~ as.character(`Days to onset`))) %>%
mutate(onset_group = case_when(
days_to_onset_cat %in% c("0", "1", "2") ~ "Rapid",
days_to_onset_cat == "Unknown" ~ "Unknown",
TRUE ~ "Delayed"
))
```
## Resistance data cleaning
```{r}
## Subset of resistance markers, for individual ST trees
resistance_subset <- subset(kleb_clin, select = c(`Read accession`, bla_esbl_acquired, bla_carb_acquired, a_gly_acquired, mls_acquired, sul_acquired, tmt_acquired, yersiniabactin, `Sequence type category`)) %>% mutate_all(~ gsub("\\.v[12]", "", gsub("[\\^\\*]", "", sub("[\\^\\*]+$", "", .)))) ##Removing any of the * or ^ and .v1 and .v2 suffixes, for the purpose of plotting
## All resistance markers for tree of all isolates
all_res <- subset(kleb_clin, select = c(`Read accession`, bla_esbl_acquired, bla_carb_acquired, bla_acquired, flq_acquired, phe_acquired, tet_acquired, rif_acquired, a_gly_acquired, mls_acquired, sul_acquired, tmt_acquired, yersiniabactin, `Sequence type category`)) %>% mutate_all(~ gsub("\\.v[12]", "", gsub("[\\^\\*]", "", sub("[\\^\\*]+$", "", .)))) ##Removing any of the * or ^ and .v1 and .v2 suffixes, for the purpose of plotting
# List column names which need splitting (by ;)
cols <- c("bla_esbl_acquired","bla_carb_acquired","a_gly_acquired","mls_acquired","sul_acquired","tmt_acquired")
all_cols <- c("bla_esbl_acquired","bla_carb_acquired","bla_acquired", "flq_acquired", "phe_acquired", "tet_acquired", "rif_acquired", "a_gly_acquired","mls_acquired","sul_acquired","tmt_acquired")
#Function to split columns by ; and give them their own column in a new dataframe
split_cols_precisely <- function(df, cols) {
unique_vals <- unique(unlist(strsplit(as.vector(as.matrix(df[, cols])), ";"))) # Trim white spaces and ensure unique values are correct
unique_vals <- trimws(unique_vals)
for (val in unique_vals) {
val <- trimws(val) # Create columns and ensure exact matching
df[[val]] <- apply(df[, cols], 1, function(x) ifelse(val %in% unlist(strsplit(as.character(x), ";")), val, NA)) # 1 0
}
return(df)
}
# Run split function and remove original unsplit columns
res_split_subset <- split_cols_precisely(resistance_subset, cols) %>% select(-one_of(cols)) %>%
rename_with(~ ifelse(. %in% c("CTX-M-14", "CTX-M-15", "TEM-116", "NDM-5", "OXA-1", "TEM-1", "TEM-1D", "LAP-2"), paste0("bla-", .), .), everything()) # Add bla- prefix
res_split_all <- split_cols_precisely(all_res, all_cols) %>% select(-one_of(all_cols)) %>%
rename_with(~ ifelse(. %in% c("CTX-M-14", "CTX-M-15", "TEM-116", "NDM-5", "OXA-1", "TEM-1", "TEM-1D", "LAP-2"), paste0("bla-", .), .), everything()) # Add bla- prefix
```
## Table 1 data
```{r}
table_1 <- kleb_clin %>%
mutate(`Sequence type` = ifelse(`Sequence type` == "ST307-1LV", "ST307", `Sequence type`)) %>%
group_by(`Sequence type`, `K locus`, `K type`, `O locus`, `O type`) %>%
summarise(count = n(), .groups = "drop") %>%
group_by(`Sequence type`) %>%
mutate(total_count = sum(count)) %>%
arrange(desc(total_count), desc(count)) %>%
select(-total_count) # optional: remove the helper column
table_1
```
## Table 2
```{r}
summary_tab <- kleb_clin %>%
mutate(culture_date_status = if_else(!is.na(`Days to onset`), "Present", NA)) %>%
mutate(admission_date_status = if_else(!is.na(week_number), "Present", NA)) %>%
mutate(`Birth location` = na_if(`Birth location`, "Unknown")) %>%
mutate(days_to_onset_cat = case_when(
is.na(`Days to onset`) ~ "Unknown",
`Days to onset` < 0 ~ "Unknown",
`Days to onset` >= 8 ~ "8+ days",
TRUE ~ as.character(`Days to onset`)))
table_2 <- summary_tab %>%
mutate(`Neonate gender` = recode(`Neonate gender`,
`1` = "Female",
`2` = "Male")) %>%
mutate(`Outcome` = recode(`Outcome`,
`0` = "Discharged",
`1` = "Died")) %>%
mutate(days_to_onset_cat = factor(as.character(days_to_onset_cat), levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8+ days"))) %>%
select(`Neonate gender`, admission_date_status, culture_date_status, `Outcome`, `Days to onset`, `Birth location`, `Study timepoint`, days_to_onset_cat, `Days to outcome`, `Days to onset`) %>%
tbl_summary(by = `Study timepoint`,
include = c(`Neonate gender`,
admission_date_status,
culture_date_status,
`Outcome`,
`Birth location`,
days_to_onset_cat,
`Study timepoint`),
sort = list(
`Neonate gender` ~ "frequency",
culture_date_status ~ "frequency",
`Outcome` ~ "frequency",
`Birth location` ~ "frequency"),
#sort = all_categorical() ~ "frequency",
type = all_continuous() ~ "continuous2",
statistic = all_continuous() ~ c(
"{N_nonmiss}",
"{median} ({p25}, {p75})",
"{min}, {max}"
),
label = list(
`Neonate gender` ~ "Neonate sex",
admission_date_status ~ "Admission Date",
culture_date_status ~ "Culture Date",
`Outcome` ~ "Clinical outcome",
`Birth location` ~ "Birth location",
days_to_onset_cat ~ "Days to onset from admission"
)) %>%
add_n(statistic = "{N_nonmiss}", footnote = T) %>% ## Only show count of non-missing values
bold_labels()
table_2
```
## Figure 1
```{r, warning=FALSE}
# Load pathogenwatch tree of all genomes
all_st_tree <- read.tree("output_trees/pathogenwatch_allst_nj_tree.nwk") %>% midpoint.root()
# Change negative branch lengths to 0
all_st_tree$edge.length <- pmax(all_st_tree$edge.length, 0.0)
# Extract tree tipnames
all_tips <- as.data.frame(get_taxa_name(ggtree(all_st_tree))) %>% setNames('all_tips')
# Create acquired resistance gene heatmap dataframe just for st307
all_res_data <- left_join(all_tips, res_split_all, by = c("all_tips" = "Read accession"))
# Clean up resistance data
all_res_data <- all_res_data %>%
mutate_if(is.factor, as.character) %>%
mutate(across(everything(), ~na_if(., "-"))) %>% #Replace all "-" entries with NA
select_if(~ !all(is.na(.))) %>% #Remove columns that are entirely NA.
arrange(factor(all_tips, levels = all_tips)) %>% #Reorder rows based on the all_tips vector
mutate_all(as.factor)
# Assign each resistance gene to its drug class
allst_group_info <- data.frame(
column = colnames(all_res_data),
group = c("None", "Yersiniabactin", "None", "Bla ESBL", "Bla ESBL", "Bla ESBL", "Carbapenemase", "Bla", "Bla", "Bla", "Bla", "Quinolone", "Quinolone", "Quinolone", "Quinolone", "Phenicol", "Phenicol", "Tetracycline", "Tetracycline", "Rifampicin", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Macrolides", "Macrolides", "Sulfonamide", "Sulfonamide", "Trimethoprim", "Trimethoprim", "Trimethoprim", "Trimethoprim", "Trimethoprim"))
allst_res_data_long <- all_res_data %>% pivot_longer(cols = -c(`Sequence type category`, all_tips), names_to = "column", values_to = "Genes") %>% left_join(allst_group_info, by = "column") %>%
mutate(group = ifelse(!is.na(Genes), group, NA))
allst_res_data_long$all_tips <- factor(allst_res_data_long$all_tips, levels = rev(unique(all_tips$all_tips))) ## Needed to flip the y axis of the heatmap to align to tree tips
# Heatmap
hm_allst <- allst_res_data_long %>%
filter(!is.na(group)) %>%
ggplot(aes(x = column, y = all_tips, fill = group)) +
geom_tile() +
facet_grid(. ~ group, scales = "free_x", space = "free_x") +
scale_fill_manual(name = "", values = all_res_colours, na.value = 'white', na.translate = FALSE) +
scale_x_discrete() +
scale_y_discrete() +
theme_minimal() +
labs(title = "", x = "") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 60, hjust = 1, vjust = 1, size = 11), axis.title.y = element_blank(), legend.position = "top", strip.text = element_blank(), legend.text = element_text(size = 12))
all_t <- ggtree(all_st_tree) %<+% allst_res_data_long
all_t_tree <- all_t + geom_tippoint(aes(colour=`Sequence type category`), shape = 19, size = 3) +
#geom_tiplab(size = 1) +
scale_colour_manual(values = st_colours) + theme(legend.position = "top", legend.justification.top = "right", legend.text = element_text(size = 12), legend.title = element_blank())
# Change order of ST data
all_t_tree$data$`Sequence type category` <- factor(all_t_tree$data$`Sequence type category`, levels=c("ST307", "ST2004", "ST983", "ST5856", "ST101", "ST985", "ST147", "ST15", "ST1119", "Other"))
# Plot
fig1 <- plot_grid(all_t_tree, hm_allst, align = "h", axis = "bt", ncol = 2, nrow = 1, rel_widths = c(1, 1.5))
fig1
#ggsave("figures/Figure_1.png", width=12, height=10)
```
## Figure 2
```{r}
# Figure 2A timeline of infections for all STs
timevcase_all_st <- kleb_clin %>%
filter(!is.na(week_number)) %>%
ggplot(aes(x = week_number, y = `Sequence type category`)) +
geom_count(aes(color = as.factor(`Sequence type category`))) +
scale_colour_manual(values = st_colours, guide = "none") +
labs(title = '',
x = 'Study week',
y = '') +
scale_y_discrete(name = "") +
geom_vline(xintercept = 31, colour = 'black') +
#theme_minimal(base_size = 15) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), legend.title = element_blank(), text = element_text(), axis.title.y = element_blank()) +
theme_minimal()
# Count the number of observations each study month per ST
monthly_st_counts <- kleb_clin %>%
filter(!is.na(month_number)) %>%
group_by(month_number, `Sequence type category`) %>%
summarise(total_count = n(), .groups = "drop")
# Calculate the total number of isolates per month across all ST categories
monthly_counts <- monthly_st_counts %>%
group_by(month_number) %>%
summarise(month_total = sum(total_count))
# Plot a bar chart of the number of infections by ST per study month
bar_chart_st <- ggplot(monthly_st_counts, aes(x = month_number, y = total_count, fill = `Sequence type category`)) +
geom_bar(stat = "identity", alpha = 0.8) +
scale_x_continuous(breaks = seq(min(monthly_st_counts$month_number, na.rm = TRUE),
max(monthly_st_counts$month_number, na.rm = TRUE),
by = 2)) + # Show ticks every 2 months
labs(fill = "") +
ylim(0, 70) +
scale_fill_manual(values = st_colours) +
labs(title = "",
x = "Study month", y = "") +
geom_vline(xintercept = 7.5, colour = 'black') +
theme_minimal() + #base_size = 15
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), legend.title = element_blank(), axis.title.y = element_blank(), text = element_text())
# Add value labels for total number of infections per study month for all STs combined
bar_chart_st2 <- bar_chart_st +
geom_text(data = monthly_counts,
aes(x = month_number, y = month_total, label = month_total),
vjust = -0.5, size = 3,
inherit.aes = FALSE)
fig2 <- timevcase_all_st / bar_chart_st2 + plot_annotation(tag_levels = "A")
fig2
#ggsave("figures/Figure_2.png", width=8, height=8)
```
## Phylogenetic trees ST307, ST2004 and ST101
```{r, warning=FALSE}
st307 <- read.tree("output_trees/final_st307_bootstrapped_tree.tre") %>% midpoint.root()
st307_tips <- as.data.frame(get_taxa_name(ggtree(st307))) %>% setNames('st307_tips')
st307_t <- ggtree(st307) #+ geom_tiplab(size = 1, align=F)
st101 <- read.tree("output_trees/final_st101_bootstrapped_tree.tre") %>% midpoint.root()
st101_tips <- as.data.frame(get_taxa_name(ggtree(st101))) %>% setNames('tips')
st101_t <- ggtree(st101) #+ geom_tiplab(size = 3, align = F)
st2004 <- read.tree("output_trees/final_st2004_bootstrapped_tree.tre") %>% midpoint.root()
st2004_tips <- as.data.frame(get_taxa_name(ggtree(st2004))) %>% setNames('tips')
st2004_t <- ggtree(st2004) #+ geom_treescale(x = 0, y = 0, width = 5, fontsize = 3, linesize = 1)
```
## Figure 4
```{r, warning=FALSE}
######### ST307 #########
# Filter data to just ST307
st307_kleb <- kleb_clin %>%
filter(`Sequence type category` == 'ST307')
# Load cluster data ST307
st307_clusters <- read_csv("output_clusters/clusters_data_st307.csv")
# Join cluster data and metadata, label non-clustered isolates and adjust cluster numbers
ordered_data307 <- st307_kleb %>%
left_join(st307_clusters %>% select(id, Cluster), by = c(`Read accession` = "id")) %>% ########
mutate(Cluster = case_when(
grepl("ERR15165515", `Read accession`) ~ "NC", # Label only non-clustered sequence
Cluster == 4 ~ "3",
Cluster == 3 ~ "4",
is.na(Cluster) ~ "Missing data", # Assign "Missing data" to NA values
TRUE ~ as.character(Cluster) # Keep other cluster values unchanged
)) %>%
mutate(`Read accession` = factor(`Read accession`, levels = st307_tips$st307_tips)) %>%
arrange(`Read accession`) %>%
mutate(`Read accession` = factor(`Read accession`, levels = rev(levels(`Read accession`)))) # flip the y axis to match tree labels
# Plot of infections over time, by cluster
plot307 <- ordered_data307 %>%
ggplot(aes(x = week_number, y = `Read accession`)) +
geom_point(aes(colour = as.factor(Cluster)), size = 2, shape = 21, fill = "white", stroke = 2) + ##shape = onset_group, size = 2.5
scale_colour_manual(values = clusters_cols, name = "Cluster number") +
#scale_shape_manual(values = c("Rapid" = 1, "Delayed" = 17, "Unknown" = 4), na.translate = TRUE, name = "Onset category") +
labs(title = '',
x = '') +
scale_x_continuous(limits = c(0, 75), breaks = seq(0, 75, by = 8)) +
theme_minimal() +
geom_vline(xintercept = 31, colour = 'black') +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), axis.text.y = element_blank(), axis.title.y = element_blank(), panel.grid.minor.x = element_blank(),plot.title = element_text(hjust = 1), legend.position = "right", axis.title.x = element_blank())
# Create acquired resistance gene heatmap dataframe just for st307
st307_res_data <- left_join(st307_tips, res_split_subset, by = c("st307_tips" = "Read accession"))
st307_res_data[] <- lapply(st307_res_data, as.factor)
st307_res_data <- st307_res_data %>%
mutate_if(is.factor, as.character) %>%
select_if(~ !all(is.na(.))) %>%
arrange(factor(st307_tips, levels = st307_tips)) %>%
select(-all_of(c("-", "strA", "strB"))) %>% ## These genes are not relevant to resistance, and also columns are removed if cases of * or ^ have the same profile as the gene without it
mutate_all(~ na_if(., '-')) %>%
mutate_all(as.factor)
# Assign each resistance gene to its drug class
st307_group_info <- data.frame(
column = colnames(st307_res_data),
group = c("None", "Yersiniabactin", "None", "Bla ESBL", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Macrolides", "Macrolides", "Sulfonamide", "Sulfonamide", "Trimethoprim", "Trimethoprim", "Trimethoprim" ))
# Add additional metadata for a second heatmap
add_data_307 <- ordered_data307 %>%
select(`Read accession`, `Birth location`, onset_group) %>%
pivot_longer(cols = c(`Birth location`, onset_group),
names_to = "column_2",
values_to = "onset_location_groups")
st307_res_data_long <- st307_res_data %>% pivot_longer(cols = -c(`Sequence type category`, st307_tips), names_to = "column", values_to = "Genes") %>% left_join(st307_group_info, by = "column") %>%
mutate(st307_tips = factor(st307_tips, levels = st307$tip.label)) %>% ## This is necessary in order to colour the heatmap by genes present but also the group they belong to
mutate(group = ifelse(!is.na(Genes), group, NA))
st307_res_add_data_long <- left_join(st307_res_data_long, add_data_307, by = c("st307_tips" = "Read accession"))
st307_res_add_data_long$st307_tips <- factor(st307_res_add_data_long$st307_tips, levels = rev(unique(st307_tips$st307_tips))) ## Needed to flip the y axis of the heatmap to match tree tips
# resistance data heatmap
hm_plot <- ggplot(st307_res_add_data_long, aes(x = column, y = st307_tips, fill = group)) +
geom_tile() +
scale_fill_manual(name = "Drug class", values = res_colours, na.value = 'white', na.translate = FALSE) +
scale_x_discrete() +
scale_y_discrete() +
theme_minimal() +
coord_fixed(ratio=0.1) +
labs(title = "", x = "") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "right", axis.title.x = element_blank())
# Reorder metadata legend order
st307_res_add_data_long$onset_location_groups <- factor(
st307_res_add_data_long$onset_location_groups,
levels = c("Inborn", "Outborn", "Rapid", "Delayed", "Unknown")
)
# metadata heatmap
hm_plot2 <- ggplot(st307_res_add_data_long, aes(x = column_2, y = st307_tips, fill = onset_location_groups)) +
geom_tile() +
scale_fill_manual(values = c(
"Inborn" = "black",
"Outborn" = "grey",
"Rapid" = "black",
"Delayed" = "grey",
"Unknown" = "white"),
labels = c(
"Inborn" = "Inborn",
"Outborn" = "Outborn",
"Rapid" = "Rapid-onset",
"Delayed" = "Delayed-onset",
"Unknown" = "Unknown"
), name = "Metadata", na.value = 'white', na.translate = FALSE) +
scale_x_discrete(labels = c("onset_group" = "Onset category")) +
scale_y_discrete() +
coord_fixed(ratio=0.1) +
theme_minimal() +
labs(title = "", x = "") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "right", axis.title.x = element_blank())
# Label tree tips with cluster number
st307_t$data <- left_join(st307_t$data, ordered_data307, by = c("label" = "Read accession"))
st307_t_labs <- st307_t + geom_tippoint(aes(color=Cluster), size=2, shape = 21, fill = "white", stroke = 2) + scale_colour_manual(values = clusters_cols, name = "") + labs(title = 'ST307') + guides(color = "none") + theme_tree2()
# Plot
fig4a <- (st307_t_labs + hm_plot + hm_plot2 + plot307) +
plot_layout(ncol = 4) &
theme(legend.position = "right")
######### ST101 #########
st101_kleb <- kleb_clin %>%
filter(`Sequence type category` == 'ST101')
### Load cluster data - this is based on SNP dists from coresnpfilter set to 80%
st101_clusters <- read_csv("output_clusters/clusters_data_st101.csv")
st101_res_data <- left_join(st101_tips, res_split_subset, by = c("tips" = "Read accession"))
st101_res_data <- st101_res_data %>%
select_if(~ any(. != 0)) %>%
select(-all_of(c("-", "strB", "strA"))) %>%
mutate_all(~ na_if(., '-')) %>%
mutate_all(as.factor)
# Assign each resistance gene to its drug class
st101_group_info <- data.frame(
column = colnames(st101_res_data),
group = c("None", "Yersiniabactin", "None", "Bla ESBL", "Bla ESBL", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Macrolides", "Macrolides", "Sulfonamide", "Sulfonamide", "Trimethoprim", "Trimethoprim"))
ordered_data101 <- st101_kleb %>%
left_join(st101_clusters %>% select(id, Cluster), by = c(`Read accession` = "id")) %>%
mutate(Cluster = case_when(
grepl("ERR6350131|ERR6350206|ERR6350791", `Read accession`) ~ "NC", ## This removes the one sequence that isnt clustered
Cluster == 2 ~ "1",
Cluster == 1 ~ "2",
is.na(Cluster) ~ "Missing data",
TRUE ~ as.character(Cluster))) %>%
mutate(`Read accession` = factor(`Read accession`, levels = st101_tips$tips)) %>%
arrange(`Read accession`) %>%
mutate(`Read accession` = factor(`Read accession`, levels = rev(levels(`Read accession`)))) #this is essential to flip the y axis to match tree tip labels
# additional metadata
add_data_101 <- ordered_data101 %>%
select(`Read accession`, `Birth location`, onset_group) %>%
pivot_longer(cols = c(`Birth location`, onset_group),
names_to = "column_2",
values_to = "onset_location_groups")
st101_res_data_long <- st101_res_data %>% pivot_longer(cols = -c(`Sequence type category`, tips), names_to = "column", values_to = "Genes") %>% left_join(st101_group_info, by = "column") %>%
mutate(group = ifelse(!is.na(Genes), group, NA))
st101_res_add_data_long <- left_join(st101_res_data_long, add_data_101, by = c("tips" = "Read accession"))
st101_res_add_data_long$tips <- factor(st101_res_add_data_long$tips, levels = rev(unique(st101_tips$tips))) #this is essential to flip the y axis to match tree tip labels
# Plot
plot101 <- ordered_data101 %>%
mutate(onset_group = factor(`Birth location`, levels = c("Inborn", "Outborn", "unknown"))) %>%
ggplot(aes(x = week_number, y = `Read accession`)) +
geom_point(aes(colour = as.factor(Cluster)), size = 2, shape = 21, fill = "white", stroke = 2) + ## shape = onset_group,
scale_colour_manual(values = clusters_cols, name = "Cluster number") +
labs(title = '',
x = '',
y = '') +
scale_x_continuous(limits = c(0, 75), breaks = seq(0, 75, by = 8)) +
theme_minimal() +
geom_vline(xintercept = 31, colour = 'black') +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), axis.text.y = element_blank(), axis.title.y = element_blank(), panel.grid.minor.x = element_blank(),plot.title = element_text(hjust = 1), legend.position = "none", axis.title.x = element_blank())
# heatmap
hm101 <- ggplot(st101_res_data_long, aes(x = column, y = tips, fill = group)) +
geom_tile() +
scale_fill_manual(name = "Drug class", values = res_colours, na.value = 'white', na.translate = FALSE) +
scale_x_discrete() +
scale_y_discrete() +
coord_fixed(ratio=1.0) +
theme_minimal() +
labs(title = "", x = "") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "none", axis.title.x = element_blank())
# Reorder metadata legend order
st101_res_add_data_long$onset_location_groups <- factor(
st101_res_add_data_long$onset_location_groups,
levels = c("Inborn", "Outborn", "Rapid", "Delayed", "Unknown")
)
# metadata heatmap
hm101_2 <- ggplot(st101_res_add_data_long, aes(x = column_2, y = tips, fill = onset_location_groups)) +
geom_tile() +
scale_fill_manual(values = c(
"Inborn" = "black",
"Outborn" = "grey",
"Rapid" = "black",
"Delayed" = "grey",
"Unknown" = "white"),
labels = c(
"Inborn" = "Inborn",
"Outborn" = "Outborn",
"Rapid" = "Rapid-onset",
"Delayed" = "Delayed-onset",
"Unknown" = "Unknown"
), name = "Metadata", na.value = 'white', na.translate = FALSE) +
scale_x_discrete(labels = c("onset_group" = "Onset category")) +
scale_y_discrete() +
coord_fixed(ratio=1.0) +
theme_minimal() +
labs(title = "", x = "") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "none", axis.title.x = element_blank())
st101_t$data <- left_join(st101_t$data, ordered_data101, by = c("label" = "Read accession"))
# Label tree tips with cluster number
st101_t_labs <- st101_t + geom_tippoint(aes(color=Cluster), size=2, shape = 21, fill = "white", stroke = 2) + scale_colour_manual(values = clusters_cols, name = "") + labs(title = "ST101") +
guides(color = "none") + theme_tree2()
fig4b <- (st101_t_labs + hm101 + hm101_2 + plot101) +
plot_layout(ncol = 4, ) &
theme(legend.position = "none")
######### ST2004 #########
st2004_kleb <- kleb_clin %>%
filter(`Sequence type category` == 'ST2004')
st2004_clusters <- read_csv("output_clusters/clusters_data_st2004.csv")
st2004_res_data <- left_join(st2004_tips, res_split_subset, by = c("tips" = "Read accession"))
st2004_res_data <- st2004_res_data %>%
select_if(~ any(. != 0)) %>%
select(-all_of(c("-", "strB", "strA"))) %>%
mutate_all(~ na_if(., '-')) %>%
select_if(~ !all(is.na(.))) %>%
mutate_all(as.factor)
st2004_group_info <- data.frame(
column = colnames(st2004_res_data),
group = c("None", "None", "Bla ESBL", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Sulfonamide", "Trimethoprim", "Trimethoprim"))
st2004_res_data_long <- st2004_res_data %>% pivot_longer(cols = -c(`Sequence type category`, tips), names_to = "column", values_to = "Genes") %>% left_join(st2004_group_info, by = "column") %>%
mutate(group = ifelse(!is.na(Genes), group, NA))
ordered_data2004 <- st2004_kleb %>%
left_join(st2004_clusters %>% select(id, Cluster), by = c(`Read accession` = "id")) %>%
mutate(Cluster = case_when(Cluster == 2 ~ "1", # Keep existing 2 values unchanged
Cluster == 1 ~ "2",
is.na(week_number) ~ "Missing data", ## remaining st2004 NAs should just be unclustered
is.na(Cluster) ~ "NC",
TRUE ~ "1")) %>% ## all other ST's are in 1 cluster per st
mutate(`Read accession` = factor(`Read accession`, levels = st2004_tips$tips)) %>%
arrange(`Read accession`) %>%
mutate(`Read accession` = factor(`Read accession`, levels = rev(levels(`Read accession`)))) #this is essential to flip the y axis as atm its the opposite way round to the tree labels
# additional metadata
add_data_2004 <- ordered_data2004 %>%
select(`Read accession`, `Birth location`, onset_group) %>%
pivot_longer(cols = c(`Birth location`, onset_group),
names_to = "column_2",
values_to = "onset_location_groups")
st2004_res_add_data_long <- left_join(st2004_res_data_long, add_data_2004, by = c("tips" = "Read accession"))
st2004_res_add_data_long$tips <- factor(st2004_res_add_data_long$tips, levels = rev(unique(st2004_tips$tips))) #this is essential to flip the y axis to match tree tip labels
# Plot
plot2004 <- ordered_data2004 %>%
ggplot(aes(x = week_number, y = `Read accession`)) +
geom_point(aes(colour = as.factor(Cluster)), size = 2, shape = 21, fill = "white", stroke = 2) +
scale_colour_manual(values = clusters_cols, name = "Cluster number") +
labs(title = '',
x = 'Study week',
y = '') +
scale_x_continuous(limits = c(0, 75), breaks = seq(0, 75, by = 8)) +
theme_minimal() +
geom_vline(xintercept = 31, colour = 'black') +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), axis.text.y = element_blank(), axis.title.y = element_blank(), panel.grid.minor.x = element_blank(),plot.title = element_text(hjust = 1), legend.position = "none")
# heatmap
hm2004 <- ggplot(st2004_res_add_data_long, aes(x = column, y = tips, fill = group)) +
geom_tile() +
#facet_wrap(~ group, scales = "free_x", nrow = 1, ncol = 10) +
scale_fill_manual(name = "Drug class", values = res_colours, na.value = 'white', na.translate = FALSE) +
scale_x_discrete() +
scale_y_discrete() +
coord_fixed(ratio=0.1) +
theme_minimal() +
labs(title = "", x = "Acquired resistance genes") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "none")
# Reorder metadata legend order
st2004_res_add_data_long$onset_location_groups <- factor(
st2004_res_add_data_long$onset_location_groups,
levels = c("Inborn", "Outborn", "Rapid", "Delayed", "Unknown")
)
# metadata heatmap
hm2004_2 <- ggplot(st2004_res_add_data_long, aes(x = column_2, y = tips, fill = onset_location_groups)) +
geom_tile() +
scale_fill_manual(values = c(
"Inborn" = "black",
"Outborn" = "grey",
"Rapid" = "black",
"Delayed" = "grey",
"Unknown" = "white"),
labels = c(
"Inborn" = "Inborn",
"Outborn" = "Outborn",
"Rapid" = "Rapid-onset",
"Delayed" = "Delayed-onset",
"Unknown" = "Unknown"
), name = "Metadata", na.value = 'white', na.translate = FALSE) +
scale_x_discrete(labels = c("onset_group" = "Onset category")) +
scale_y_discrete() +
coord_fixed(ratio=0.1) +
theme_minimal() +
labs(title = "", x = "Metadata") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "none")
st2004_t$data <- left_join(st2004_t$data, ordered_data2004, by = c("label" = "Read accession"))
# Label tree tips with cluster number
st2004_t_labs <- st2004_t + geom_tippoint(aes(color=Cluster), size = 2, shape = 21, fill = "white", stroke = 2) + scale_colour_manual(values = clusters_cols, name = "") + labs(title = "ST2004") + guides(color = "none") + theme_tree2()
# Plot
fig4c <- (st2004_t_labs + hm2004 + hm2004_2 + plot2004) +
plot_layout(ncol = 4) &
theme(legend.position = "none")
# Final joint plot
fig4_all <- fig4a / fig4b /fig4c + plot_layout(guides = "collect", heights = c(2, 2, 1))
fig4_all
#ggsave("figures/Figure_4.png", width=10, height=12)
```
## Supplementary figure 4
```{r, warning=FALSE}
######### 'Other' sequence types #########
# Add cluster data
other_st_kleb <- kleb_clin %>%
filter(!`Sequence type category` %in% c('ST307', 'ST101', 'ST2004')) %>%
filter(!is.na(week_number)) %>%
mutate(Cluster = case_when(`Sequence type category` == 'Other' ~ "NC",
TRUE ~ "1"))
# Sort isolates by cluster
other_st_kleb <- other_st_kleb %>%
arrange(Cluster, `Read accession`) %>% # Sort isolates by Cluster first
mutate(`Read accession` = factor(`Read accession`, levels = unique(`Read accession`)))
# Extract relevant IDs
other_st_kleb_ids <- other_st_kleb %>%
select(`Read accession`, Cluster)
# Join resistance data
other_res_data <- left_join(other_st_kleb_ids, res_split_subset) %>% mutate_all(as.factor)
# Clean and filter resistance data
other_res_data <- other_res_data %>%
mutate_if(is.factor, as.character) %>%
select_if(~ any(. != 0)) %>%
select(-all_of(c("-", "strB", "strA"))) %>%
mutate_all(~ na_if(., '-'))
group_info_all_genes <- data.frame(
column = colnames(other_res_data),
group = c("None", "None", "Yersiniabactin", "None", "Bla ESBL", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Aminoglycosides", "Macrolides", "Macrolides", "Sulfonamide", "Sulfonamide", "Trimethoprim", "Trimethoprim", "Trimethoprim", "Trimethoprim"))
other_res_data_long <- other_res_data %>% pivot_longer(cols = -c(`Sequence type category`, `Read accession`, Cluster), names_to = "column", values_to = "Genes") %>% left_join(group_info_all_genes, by = "column") %>%
mutate(group = ifelse(!is.na(Genes), group, NA)) %>%
filter(!is.na(`Read accession`))
# additional metadata
add_data_other <- other_st_kleb %>%
select(`Read accession`, `Birth location`, onset_group) %>%
pivot_longer(cols = c(`Birth location`, onset_group),
names_to = "column_2",
values_to = "onset_location_groups")
other_res_add_data_long <- left_join(other_res_data_long, add_data_other) %>% mutate_all(as.factor)
# Plot infections over time
plot_others <- other_st_kleb %>%
ggplot(aes(x = week_number, y = `Read accession`)) +
geom_point(aes(colour = as.factor(Cluster)), size = 2.5, shape = 21, fill = "white", stroke = 2) + ##shape = onset_group,
scale_colour_manual(values = clusters_cols, name = "Cluster number") +
labs(title = '',
x = 'Study week',
y = '') +
scale_x_continuous(limits = c(0, 75), breaks = seq(0, 75, by = 4)) +
theme_minimal() +
geom_vline(xintercept = 31, colour = 'black') +
guides(colour = guide_legend(title = "Cluster number")) +
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1), axis.text.y = element_blank(), plot.title = element_text(hjust = 1, vjust = -1), legend.position = "none")
# Facet plot by ST
plot_others <- plot_others +
facet_grid(rows = vars(`Sequence type category`), scales = "free_y", space = "free_y") +
theme(strip.text.y = element_text(size = 17, angle = 0), strip.placement = "outside")
other_res_add_data_long_sort <- other_res_add_data_long %>%
arrange(Cluster, `Read accession`) %>% # Sort isolates by Cluster first
mutate(`Read accession` = factor(`Read accession`, levels = unique(`Read accession`))) # Convert to ordered factor
# Plot AMR genes
other_st_amr <- ggplot(other_res_add_data_long_sort, aes(x = column, y = `Read accession`, fill = group)) +
geom_tile() +
scale_fill_manual(name = "Drug class", values = res_colours, na.value = 'white', na.translate = FALSE) +
scale_x_discrete() +
scale_y_discrete() +
#coord_fixed(ratio=0.1) +
facet_grid(rows = vars(`Sequence type category`), scales = "free_y", space = "free_y") +
theme_minimal() +
labs(title = "", x = "Acquired resistance genes") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 75, hjust = 1, vjust = 1), axis.title.y = element_blank(), legend.position = "none", strip.text.y = element_blank())
# You need to subset other_res_add_data_long_sort so that it only includes rows relevant to the metadata columns you're plotting
other_hm2_data <- other_res_add_data_long_sort %>%
filter(column_2 %in% c("onset_group", "Birth location"))
# Reorder metadata legend order
other_hm2_data$onset_location_groups <- factor(
other_hm2_data$onset_location_groups,
levels = c("Inborn", "Outborn", "Rapid", "Delayed", "Unknown")
)
# metadata heatmap
other_hm2 <- ggplot(other_hm2_data, aes(x = column_2, y = `Read accession`, fill = onset_location_groups)) +
geom_tile() +
scale_fill_manual(values = c(
"Inborn" = "black",
"Outborn" = "grey",
"Rapid" = "black",
"Delayed" = "grey",
"Unknown" = "white"),
labels = c(
"Inborn" = "Inborn",
"Outborn" = "Outborn",
"Rapid" = "Rapid-onset",
"Delayed" = "Delayed-onset",
"Unknown" = "Unknown"
),
name = "Metadata", na.value = 'white', na.translate = FALSE) +
scale_x_discrete(labels = c("onset_group" = "Onset category")) +
scale_y_discrete() +
#coord_fixed(ratio=0.1) +
facet_grid(rows = vars(`Sequence type category`), scales = "free_y", space = "free_y") +
theme_minimal() +
labs(title = "", x = "Metadata") +
theme(axis.text.y = element_blank(), axis.text.x = element_text(angle = 75, hjust = 1, vjust = 1), axis.title.y = element_blank(), strip.text.y = element_blank(), legend.position = "right")
fig_s4 <- (other_st_amr + other_hm2 + plot_others ) +
plot_layout(ncol = 3, guides = "collect", widths = c(3, 0.5, 3)) &
theme(legend.position = "right")
fig_s4
#ggsave("figures/Supplementary_figure_4.png", width=10, height=10)
```
## Stats and summary numbers
```{r}
# Final number of high-quality K. pneumoniae genomes after all filtering
nrow(kleb_clin)
# Number of STs, with one case of ST307-1LV grouped into ST307
kleb_clin %>% mutate(`Sequence type` = ifelse(`Sequence type` == "ST307-1LV", "ST307", `Sequence type`)) %>% group_by(`Sequence type`) %>% count() %>% nrow()
# Proportions of each ST (of ≥4 genomes)
ST_prop <- kleb_clin %>%
count(`Sequence type category`) %>% # counts occurrences of each ST
mutate(proportion = n / sum(n)*100) # calculate proportion for each ST
# Count of K locus & type and O locus & type combinations, per ST
ko_tab <- kleb_clin %>%
group_by(`Sequence type category`, `O locus`, `O type`, `K locus`, `K type`) %>%
summarise(count = n(), .groups = "drop") %>%
group_by(`Sequence type category`) %>%
mutate(total_count = sum(count)) %>%
arrange(desc(total_count), desc(count)) %>%
select(-total_count) # optional: remove the helper column
# Columns to select from dataframe of acquired resistance and virulence genes
acq_gene_columns <- c("a_gly_acquired", "flq_acquired", "mls_acquired", "phe_acquired", "rif_acquired", "sul_acquired", "tet_acquired", "tmt_acquired", "bla_acquired", "bla_esbl_acquired", "bla_carb_acquired", "yersiniabactin")
# Summary counts and proportions of cases with acquired resistance for each Abx, and virulence genes
resistance_count <- kleb_clin %>%
summarise(across(
all_of(acq_gene_columns),
~sum(. != "-"),
.names = "Genomes_with_acquired_resistance_genes_in_{.col}"
)) %>%
pivot_longer(everything(),
names_to = "Column",
values_to = "RowCount") %>%
mutate(Proportion = round(RowCount / nrow(kleb_clin)*100, 1))
# Number of isolates with associated clinical metadata
kleb_clin %>% filter(!is.na(week_number)) %>% nrow()
# Number of isolates with associated clinical metadata including a date of admission
kleb_clin %>% filter(!is.na(`Days to onset`)) %>% nrow()
# Create a filtered dataframe of only isolates collected at study baseline
stats_tab_subset_b <- kleb_clin %>%
filter(!is.na(`Days to onset`)) %>%
filter(`Study timepoint` == "Baseline")
# Create a filtered dataframe of only isolates collected post-implementation
stats_tab_subset_pi <- kleb_clin %>%
filter(!is.na(`Days to onset`)) %>%
filter(`Study timepoint` == "Post-implementation")
# Days to onset summary stats for baseline cases
summary(stats_tab_subset_b$`Days to onset`)
# Days to onset summary stats for post-implementation cases
summary(stats_tab_subset_pi$`Days to onset`)
# Contingency table of days to onset for each timepoint
stats_tab_filt <- kleb_clin %>% filter(!days_to_onset_cat == "Unknown")
# Contingency table of Rapid or late onset infection for both timepoints
t_el <- table(stats_tab_filt$`Study timepoint`, stats_tab_filt$onset_group)
# Number of Rapid onset infections in each timepoint
onset_early <- c(t_el["Baseline", "Rapid"], t_el["Post-implementation", "Rapid"])
total_births <- rowSums(t_el) # total births for each timepoint
# Test whether the proportion of Inborn neonates changes between timepoints.
prop.test(x = onset_early, n = total_births)
# Number of neonates with a recorded location of birth
kleb_clin %>% filter(!`Birth location` == "Unknown") %>% nrow()
# Total neonates Inborn and outborn
birth_loc_prop <- kleb_clin %>%
filter(`Birth location` != "Unknown") %>%
count(`Birth location`) %>%
mutate(proportion = n / sum(n)*100)
birth_loc <- kleb_clin %>% filter(!`Birth location` == "Unknown")
# Contingency table of birth location for both timepoints
t1 <- table(birth_loc$`Study timepoint`, birth_loc$`Birth location`)
# Number of Inborn neonates in each timepoint
birth_loc_UTH <- c(t1["Baseline", "Inborn"], t1["Post-implementation", "Inborn"])
total_births <- rowSums(t1) # total births for each timepoint
# Test whether the proportion of Inborn neonates changes between timepoints.
prop.test(x = birth_loc_UTH, n = total_births)
# Number of samples taken within the baseline and post-implementation periods
table(kleb_clin$`Study timepoint`)
##########################################
# Calculating the total, mean and median number of infections per ST, per study timepoint
# Baseline
weekly_infection_stats_baseline <- function(data, sequence_list, max_week = 31) {
results <- lapply(sequence_list, function(st) {
# Filter and summarize baseline data
weekly_stats <- data %>%
filter(`Sequence type category` == st) %>%
filter(week_number <= max_week) %>%
group_by(week_number, `Sequence type category`) %>%
summarise(total_count = n(), .groups = "drop")
# Create full week sequence
min_week <- min(weekly_stats$week_number, na.rm = TRUE)
max_week <- max(weekly_stats$week_number, na.rm = TRUE)
full_weeks <- data.frame(week_number = seq(min_week, max_week))
# Join and fill missing weeks with 0
weekly_stats <- full_weeks %>%
mutate(`Sequence type category` = st) %>%
left_join(weekly_stats, by = c("week_number", "Sequence type category")) %>%
mutate(total_count = ifelse(is.na(total_count), 0, total_count))
# 🔍 Print the weekly_stats for inspection
cat("\n--- Weekly Stats for:", st, "---\n")
print(weekly_stats)
# Return summary stats
data.frame(
Sequence = st,
Sum = sum(weekly_stats$total_count),
Median = median(weekly_stats$total_count),
Mean = round(mean(weekly_stats$total_count),2),
Week_Range = paste(min_week, max_week, sep = "–")
)
})
#names(results) <- sequence_list
#return(results)
do.call(rbind, results)
}
sequence_list_baseline <- c('ST307', 'ST101', 'ST2004', 'ST985', 'ST147')
baseline_stats <- weekly_infection_stats_baseline(kleb_clin, sequence_list_baseline)
## Post-implementation
weekly_infection_stats_pi <- function(data, sequence_list, max_week = 31) {
results <- lapply(sequence_list, function(st) {
# Filter and summarize baseline data
weekly_stats <- data %>%
filter(`Sequence type category` == st) %>%
filter(week_number > max_week) %>%
group_by(week_number, `Sequence type category`) %>%
summarise(total_count = n(), .groups = "drop")
# Create full week sequence
min_week <- min(weekly_stats$week_number, na.rm = TRUE)
max_week <- max(weekly_stats$week_number, na.rm = TRUE)
full_weeks <- data.frame(week_number = seq(min_week, max_week))
# Join and fill missing weeks with 0
weekly_stats <- full_weeks %>%
mutate(`Sequence type category` = st) %>%
left_join(weekly_stats, by = c("week_number", "Sequence type category")) %>%
mutate(total_count = ifelse(is.na(total_count), 0, total_count))
# Return summary stats
data.frame(
Sequence = st,
Sum = sum(weekly_stats$total_count),
Median = median(weekly_stats$total_count),
Mean = round(mean(weekly_stats$total_count),2),
Week_Range = paste(min_week, max_week, sep = "–")
)
})
do.call(rbind, results)
}
sequence_list_pi <- c('ST307', 'ST101', 'ST2004', 'ST983', 'ST15')
pi_stats <- weekly_infection_stats_pi(kleb_clin, sequence_list_pi)