-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWPI_aggregate_desc.qmd
1914 lines (1565 loc) · 70.5 KB
/
WPI_aggregate_desc.qmd
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: "NHS England Community stategy"
author: "Alexander Lawless"
date: last-modified
date-format: "DD-MM-YYYY"
title-block-banner: "#f9bf07"
title-block-banner-color: "#333739"
format:
html:
embed-resources: true
smooth-scroll: true
theme: cosmo
fontcolor: black
toc: true
toc-location: left
toc-title: Summary
toc-depth: 3
editor: visual
css: styles.css
---
```{r}
#| label: setup
#| include: false
#| echo: false
#| warning: false
library(tidyverse)
library(janitor)
library(DT)
library(sf)
library(readxl)
library(patchwork)
library(GGally)
library(plotly)
library(reshape2)
library(ggrepel)
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, message=FALSE, fig.width =12, fig.height = 9)
setwd("C:/Users/alexander.lawless/OneDrive - Midlands and Lancashire CSU/Work/1. Projects/2024_25/Community services modelling/r_repos/Community_Strategies")
# Functions/lookups ----
create_dt <- function(x) {
DT::datatable(
x
, extensions = "Buttons"
, options = list(
dom = "Blfrtip"
, buttons = c("copy", "csv")
, lengthMenu = list(
c(10, 25, 50, -1)
, c(10, 25, 50, "All")
),
width = "400px", # Specify the width
height = "200px" # Specify the height
)
)
}
ethnicity_lookup <- tribble(
~Code, ~Description,
"A", "White - British",
"B", "White - Irish",
"C", "White - Any other White background",
"D", "Mixed - White and Black Caribbean",
"E", "Mixed - White and Black African",
"F", "Mixed - White and Asian",
"G", "Mixed - Any other mixed background",
"H", "Asian or Asian British - Indian",
"J", "Asian or Asian British - Pakistani",
"K", "Asian or Asian British - Bangladeshi",
"L", "Asian or Asian British - Any other Asian background",
"M", "Black or Black British - Caribbean",
"N", "Black or Black British - African",
"P", "Black or Black British - Any other Black background",
"R", "Other Ethnic Groups - Chinese",
"S", "Other Ethnic Groups - Any other ethnic group",
"Z", "Not stated"
)
# Set SU theme ####
SU_colours <- c(
`orange` = grDevices::rgb(248, 191, 7, maxColorValue = 255), # "#f9bf07",
`charcoal` = grDevices::rgb(44, 40, 37, maxColorValue = 255), # "#2c2825",
`slate` = grDevices::rgb(104, 111, 115, maxColorValue = 255), # "#686f73",
`blue` = grDevices::rgb(88, 29, 193, maxColorValue = 255), # "#5881c1",
`red` = grDevices::rgb(236, 101, 85, maxColorValue = 255), # "#ec6555",
# additional accent colours from word doc template
`yellow` = grDevices::rgb(252, 229, 155, maxColorValue = 255),
`grey` = grDevices::rgb(163, 168, 172, maxColorValue = 255),
`white` = grDevices::rgb(255, 255, 255, maxColorValue = 255),
# light and dark ends from colour theme in word doc
`light orange` = grDevices::rgb(253, 242, 205, maxColorValue = 255),
`dark orange` = grDevices::rgb(124, 95, 3, maxColorValue = 255),
`light charcoal` = grDevices::rgb(235, 233, 231, maxColorValue = 255),
`dark charcoal` = "#000000", # black
`light slate` = grDevices::rgb(224, 226, 227, maxColorValue = 255),
`dark slate` = grDevices::rgb(51, 55, 57, maxColorValue = 255),
`light blue` = grDevices::rgb(221, 229, 242, maxColorValue = 255),
`dark blue` = grDevices::rgb(38, 61, 102, maxColorValue = 255),
`light red` = grDevices::rgb(251, 224, 220, maxColorValue = 255),
`dark red` = grDevices::rgb(144, 29, 16, maxColorValue = 255),
`light yellow` = grDevices::rgb(254, 249, 235, maxColorValue = 255),
`dark yellow` = grDevices::rgb(197, 152, 5, maxColorValue = 255),
`light grey` = grDevices::rgb(236, 237, 238, maxColorValue = 255),
`dark grey` = grDevices::rgb(79, 84, 88, maxColorValue = 255),
`light white` = grDevices::rgb(242, 242, 242, maxColorValue = 255),
`dark white` = grDevices::rgb(127, 127, 127, maxColorValue = 255),
`red2` = grDevices::rgb(215, 25, 28, maxColorValue = 255),
`orange2` = grDevices::rgb(253, 174, 97, maxColorValue = 255),
`yellow2` = grDevices::rgb(255, 255, 191, maxColorValue = 255),
`green2` = grDevices::rgb(171, 221, 164, maxColorValue = 255),
`blue2` = grDevices::rgb(43, 131, 186, maxColorValue = 255) # "#2b83ba"
)
SU_cols <- function(...) {
cols <- c(...)
if (is.null(cols)) {
return(SU_colours)
}
SU_colours[cols]
}
SU_palettes <- list(
`main` = SU_cols("orange", "charcoal", "slate", "blue", "red"),
`oranges` = SU_cols("light orange", "orange", "dark orange"),
`slates` = SU_cols("light slate", "slate", "dark slate"),
`mixed` = SU_cols("dark red", "orange", "yellow", "light blue", "slate"),
`oj_coal` = SU_cols("yellow", "orange", "red", "dark red", "dark charcoal"),
`oj_red` = SU_cols("yellow", "orange", "red", "dark red"),
`white_oj_coal` = SU_cols("white", "yellow", "orange", "red", "dark red", "dark charcoal"), # added since shared
`lyellow_oj_coal` = SU_cols("light yellow", "orange", "red", "dark red", "dark charcoal"), # added since shared
`wy_oj_coal` = SU_cols("white", "light yellow", "yellow", "orange", "red", "dark red", "charcoal", "dark charcoal"),
`red_coal` = SU_cols("red", "dark red", "charcoal", "dark charcoal"),
`blue_yellow_red` = SU_cols("red2", "orange2", "yellow2", "green2", "blue2"),
`red_yellow_blue` = SU_cols("blue2", "green2", "yellow2", "orange2", "red2")
)
SU_pal <- function(palette = "main", reverse = FALSE, ...) {
pal <- SU_palettes[[palette]]
if (reverse) pal <- rev(pal)
colorRampPalette(pal, ...)
}
scale_color_SU <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
pal <- SU_pal(palette = palette, reverse = reverse)
if (discrete) {
discrete_scale("colour", paste0("SU_", palette), palette = pal, ...)
} else {
scale_color_gradientn(colours = pal(256), ...)
}
}
scale_fill_SU <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
pal <- SU_pal(palette = palette, reverse = reverse)
if (discrete) {
discrete_scale("fill", paste0("SU_", palette), palette = pal, ...)
} else {
scale_fill_gradientn(colours = pal(256), ...)
}
}
theme_SU <- function(base_size) {
theme_minimal(
# base_family = "Segoe UI",
base_size = 12
) %+replace%
theme(
axis.title = element_text(size = 11, face = "bold", colour = SU_cols("charcoal")),
plot.title = element_text(hjust = 0, face = "bold", size = 12, colour = SU_cols("charcoal"), margin = margin(b = 4, unit = "pt")),
plot.subtitle = element_text(hjust = 0, face = "italic", size = 10, colour = SU_cols("charcoal"), margin = margin(b = 4, unit = "pt")),
plot.caption = element_text(hjust = 0, face = "italic", size = 9, colour = SU_cols("slate"), margin = margin(b = 4, unit = "pt")),
legend.text = element_text(size = 10, colour = SU_cols("charcoal")),
legend.title = element_text(face = "bold", size = 11, colour = SU_cols("charcoal"), margin = margin(b = 4, unit = "pt"))
)
}
theme_set(theme_SU())
# Access comm strat grouped data ----
aggregate_data <-
read_csv("aggregate_data_recombined.csv") |>
mutate(flag_der_falls =
case_when(!is.na(flag_fall_imp_frac) ~ flag_fall_imp_frac,
TRUE ~ flag_fall_imp_tend)) |>
filter(der_activity_month <= 202408)
aggregate_data_core_cohorts <-
aggregate_data |>
filter(!(is.na(flag_frail) & is.na(flag_eol) & is.na(flag_elderly_emergency) & is.na(flag_der_falls)))
# Split data into groups of interest ----
aggregate_data_frail <-
aggregate_data %>%
drop_na(flag_frail) %>%
mutate(year = lubridate::year(month))
aggregate_data_eol <-
aggregate_data %>%
drop_na(flag_eol) %>%
mutate(year = lubridate::year(month))
aggregate_data_falls <-
aggregate_data %>%
drop_na(flag_der_falls) %>%
mutate(year = lubridate::year(month))
#aggregate_data_falls <-
# aggregate_data %>%
# filter(!is.na(flag_falls_exp) |
# !is.na(flag_fall_imp_frac) |
# !is.na(flag_fall_imp_tend)) %>%
# mutate(year = lubridate::year(month))
aggregate_data_elderly_emergency <-
aggregate_data %>%
drop_na(flag_elderly_emergency) %>%
mutate(year = lubridate::year(month))
aggregate_data_amb_chronic <-
aggregate_data %>%
drop_na(amb_chronic) %>%
mutate(year = lubridate::year(month))
aggregate_data_amb_acute <-
aggregate_data %>%
drop_na(amb_acute) %>%
mutate(year = lubridate::year(month))
aggregate_data_amb_vacc_prev <-
aggregate_data %>%
drop_na(amb_vacc_prev) %>%
mutate(year = lubridate::year(month))
aggregate_data_eol_1_year <-
aggregate_data %>%
drop_na(death_location_type) %>%
mutate(year = lubridate::year(month))
# Mapping ----
# Read in icb lookup
icb_lookup <-
read_csv("mapping/S_ICB_ICB_to_NHSE_R.csv") %>%
clean_names() %>%
select(icb23cd, icb23cdh, icb23nm, nhser23nm) %>%
distinct()
# Import icb shp file from geoportal
icb_23_shp <-
st_read("https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/Integrated_Care_Boards_April_2023_EN_BGC/FeatureServer/0/query?outFields=*&where=1%3D1&f=geojson") %>%
clean_names()
# Age and sex adjusted population rate ----
icb_pop_2023 <-
read_excel("pop_estimates/sapehealthgeogstablefinal.xlsx",
sheet = "Mid-2022 ICB 2023", skip = 3) %>%
clean_names()
# Clean and group by ICB, sex and age-range
icb_pop_2023_sex_age_range <-
icb_pop_2023 %>%
pivot_longer(cols = starts_with("f") | starts_with("m"),
names_to = "age_sex",
values_to = "population") %>%
mutate(sex = as.numeric(ifelse(grepl("^m", age_sex), "1", "2")),
age = as.numeric(sub("^[mf]", "", age_sex))) %>%
mutate(age_range =
case_when(
age >= 0 & age <= 4 ~ "0-4",
age >= 5 & age <= 9 ~ "5-9",
age >= 10 & age <= 14 ~ "10-14",
age >= 15 & age <= 19 ~ "15-19",
age >= 20 & age <= 24 ~ "20-24",
age >= 25 & age <= 29 ~ "25-29",
age >= 30 & age <= 34 ~ "30-34",
age >= 35 & age <= 39 ~ "35-39",
age >= 40 & age <= 44 ~ "40-44",
age >= 45 & age <= 49 ~ "45-49",
age >= 50 & age <= 54 ~ "50-54",
age >= 55 & age <= 59 ~ "55-59",
age >= 60 & age <= 64 ~ "60-64",
age >= 65 & age <= 69 ~ "65-69",
age >= 70 & age <= 74 ~ "70-74",
age >= 75 & age <= 79 ~ "75-79",
age >= 80 & age <= 84 ~ "80-84",
age >= 85 & age <= 89 ~ "85-89",
age >= 90 & age <= 94 ~ "90-94",
age >= 95 & age <= 99 ~ "95-99",
age >= 100 & age <= 104 ~ "100-104",
age >= 105 ~ "105+",
TRUE ~ NA
)) %>%
#mutate(age_range =
# cut(age,
# breaks = seq(0, 90, by = 5),
# right = FALSE,
# labels = paste(seq(0, 85, by = 5))
# )
# ) %>%
group_by(icb_2023_code, icb_2023_name, sex, age_range) %>%
summarise(population = sum(population, na.rm= TRUE)) %>%
ungroup() %>%
mutate(icb_2023_name = str_replace_all(icb_2023_name, "Integrated Care Board", "ICB")) %>%
mutate(icb_name_short_trans =
case_when(
icb_2023_name == "NHS Bath and North East Somerset, Swindon and Wiltshire ICB" ~ "NHS Bath & NE S'set, S'don & W ICB",
icb_2023_name == "NHS Bedfordshire, Luton and Milton Keynes ICB" ~ "NHS Beds, Luton & Milton Keynes ICB",
icb_2023_name == "NHS Birmingham and Solihull ICB" ~ "NHS Birmingham And Solihull ICB",
icb_2023_name == "NHS Bristol, North Somerset and South Gloucestershire ICB" ~ "NHS Bristol, N S'set & S Gloucs ICB",
icb_2023_name == "NHS Buckinghamshire, Oxfordshire and Berkshire West ICB" ~ "NHS Bucks, Oxford & Berkshire W ICB",
icb_2023_name == "NHS Cambridgeshire and Peterborough ICB" ~ "NHS Cambs & Peterborough ICB",
icb_2023_name == "NHS Cornwall and the Isles of Scilly ICB" ~ "NHS Cornwall & Isles Of Scilly ICB",
icb_2023_name == "NHS Herefordshire and Worcestershire ICB" ~ "NHS Herefords & Worcestershire ICB",
icb_2023_name == "NHS Hertfordshire and West Essex ICB" ~ "NHS Hertfordshire & West Essex ICB",
icb_2023_name == "NHS Lancashire and South Cumbria ICB" ~ "NHS Lancashire & South Cumbria ICB",
icb_2023_name == "NHS Leicester, Leicestershire and Rutland ICB" ~ "NHS Leics, Leic'shire & Rutland ICB",
icb_2023_name == "NHS North East and North Cumbria ICB" ~ "NHS North East & North Cumbria ICB",
icb_2023_name == "NHS Nottingham and Nottinghamshire ICB" ~ "NHS Nott'ham & Nottinghamshire ICB",
icb_2023_name == "NHS Shropshire, Telford and Wrekin ICB" ~ "NHS Shrops, Telford & Wrekin ICB",
icb_2023_name == "NHS Staffordshire and Stoke-on-Trent ICB" ~ "NHS Staffordshire & Stoke-On-Tr ICB",
icb_2023_name == "NHS Suffolk and North East Essex ICB" ~ "NHS Suffolk & North East Essex ICB",
TRUE ~ icb_2023_name
))
# Apply standardisation to cohort sub-groups
standardisation_function <- function(data_input) {
crude_spell_rate <-
data_input %>%
mutate(year = year(month),
age_range = as.character(age_range)) %>%
group_by(year, icb_name_short, sex, age_range) %>%
summarise(spells = sum(spells)) %>%
mutate(icb_code = str_extract(icb_name_short, "^[^:]+")) %>%
left_join(icb_lookup, by = c("icb_code" = "icb23cdh")) %>%
left_join(icb_pop_2023_sex_age_range %>%
mutate(age_range = as.character(age_range)),
by = c("icb23cd" = "icb_2023_code",
"sex", "age_range"), keep = F) %>%
mutate(spell_rate = spells/population)
# Define a standard population (e.g., the total population in the dataset)
standard_population <-
icb_pop_2023_sex_age_range %>%
group_by(age_range, sex) %>%
summarise(population = sum(population))
# Merge with the standard population and calculate adjusted rate
adjusted_rate_icb <-
crude_spell_rate %>%
left_join(standard_population, by = c("age_range", "sex"), suffix = c("", "_standard")) %>%
drop_na(spell_rate) %>%
group_by(icb23cd, icb_name_short, year) %>%
summarise(adjusted_spell_rate = sum(spell_rate * population_standard) / sum(population_standard) * 1000)
adjusted_rate_icb
}
adjusted_rate_sub_cohorts <-
standardisation_function(aggregate_data) %>%
mutate(id = "rate") %>%
union_all(standardisation_function(aggregate_data_frail) %>%
mutate(id = "frail_rate")) %>%
union_all(standardisation_function(aggregate_data_falls) %>%
mutate(id = "falls_rate")) %>%
union_all(standardisation_function(aggregate_data_eol) %>%
mutate(id = "eol_rate")) %>%
union_all(standardisation_function(aggregate_data_elderly_emergency) %>%
mutate(id = "elderly_emergency_rate")) %>%
ungroup() %>%
mutate(id_clean = case_when(id == "frail_rate" ~ "A. Frail",
id == "falls_rate" ~ "C. Falls",
id == "eol_rate" ~ "D. End of life",
id == "elderly_emergency_rate" ~ "B. Emergency elderly"))
crude_spell_rate <-
aggregate_data %>%
mutate(year = year(month),
age_range = as.character(age_range)) %>%
group_by(year, icb_name_short, sex, age_range) %>%
summarise(spells = sum(spells)) %>%
mutate(icb_code = str_extract(icb_name_short, "^[^:]+")) %>%
left_join(icb_lookup, by = c("icb_code" = "icb23cdh")) %>%
left_join(icb_pop_2023_sex_age_range %>%
mutate(age_range = as.character(age_range)),
by = c("icb23cd" = "icb_2023_code",
"sex", "age_range"), keep = F) %>%
mutate(spell_rate = spells/population)
# Avg LoS by ICB
avg_los_icb_cohort <-
read_csv("avg_los_icb_cohort.csv") %>%
clean_names()
# Create pairs plot
compare_admission_rates <-
adjusted_rate_sub_cohorts |>
filter(year == 2023) |>
select(-icb23cd, -year, -id) |>
pivot_wider(id_cols = icb_name_short,
names_from = id_clean,
values_from = adjusted_spell_rate) |>
select(icb_name_short,`A. Frail`, `B. Emergency elderly`, `C. Falls`, `D. End of life`)
thresholds <- sapply(compare_admission_rates[, 2:5], function(x) quantile(x, 0.9, na.rm = T))
# Admission rate map
plot_function <- function(cohort, label) {
icb_23_shp %>%
select(icb23cd) %>%
left_join(adjusted_rate_sub_cohorts %>%
filter(id == cohort,
year == 2023) %>%
mutate(quintile = cut(adjusted_spell_rate,
breaks = quantile(adjusted_spell_rate, probs = seq(0, 1, 0.2), na.rm = TRUE),
include.lowest = TRUE,
labels = FALSE)),
by = "icb23cd") %>%
ggplot() +
geom_sf(aes(fill = factor(quintile))) +
scale_fill_brewer(palette = "YlOrRd",
name = paste0(label, ": Quintiles"),
labels = c("1st", "2nd", "3rd", "4th", "5th")) +
theme(panel.grid = element_blank(),
axis.text = element_blank())
}
frail_map <- plot_function("frail_rate", "A. Frail")
falls_map <- plot_function("falls_rate", "C. Falls")
eol_map <- plot_function("eol_rate", "D. EoL")
elderly_emergency_map <- plot_function("elderly_emergency_rate", "B. Elderly emergency")
# Plot patchwork map
combined_map_icb_rate_cohorts <-
frail_map +
elderly_emergency_map +
falls_map +
eol_map +
plot_annotation(
title = 'Mitigable activity by ICB - admission rate',
subtitle = 'SUS 2023 | Admission identified: Frail, emergency elderly, falls & end of life',
caption = 'Note: 1st quintile represents the lowest 20% admission rates'
)
# Create function to draw funell plots
funnel_plot_function <- function(cohort, subtitle_text) {
data <-
adjusted_rate_sub_cohorts |>
filter(id_clean == {{cohort}},
year == 2023) |>
left_join(icb_pop_2023_sex_age_range |>
group_by(icb_2023_code) |>
summarise(population = sum(population)),
by = c("icb23cd" = "icb_2023_code")
)
mean_rate <- mean(data$adjusted_spell_rate)
sd_rate <- sd(data$adjusted_spell_rate)
# Create the funnel plot
data |>
mutate(std_from_mean = (adjusted_spell_rate - mean_rate) / sd_rate) |>
mutate(fill_text =
case_when(std_from_mean >= 1 ~ "1. Above 1 SD",
std_from_mean <= -1 ~ "3. Below 1 SD",
TRUE ~ "2. Within 1 SD")) |>
mutate(icb_name_clean = str_sub(icb_name_short, 10,100)) |>
mutate(icb_name_clean = str_remove_all(icb_name_clean, " ICB"))|>
mutate(label = case_when(fill_text != "2. Within 1 SD" ~ icb_name_clean)) |>
ggplot(aes(x = population, y = adjusted_spell_rate,
colour = fill_text,
alpha = fill_text
)) +
geom_point(size = 4) +
geom_label_repel(aes(label = label), size = 5, show.legend = FALSE) +
geom_hline(yintercept = mean_rate, color = "blue", linetype = "dashed", linewidth = 1) +
geom_hline(yintercept = mean_rate + sd_rate, color = "red", linetype = "dotted", linewidth = 1) +
geom_hline(yintercept = mean_rate - sd_rate, color = "red", linetype = "dotted", linewidth = 1) +
scale_x_continuous(labels = scales::comma) +
scale_alpha_manual(values = c(1,0.2,1)) +
scale_color_SU() +
labs(x = "Population",
y = "Adjusted admission rate per 1,000",
title = "Variation in admission rates by ICB and underlying population",
subtitle = paste0("Subcohort: ", subtitle_text, " | 2023"),
colour = "",
alpha = ""
)
}
# 2x2 plots to compare admission rates in 2 cohorts on 1 graph
compare_2_2_plots <- function(cohort_1, cohort_2, cohort_1_axis, cohort_2_axis) {
data_cohort_1 <-
adjusted_rate_sub_cohorts |>
filter(id_clean == {{cohort_1}},
year == 2023)
mean_rate_cohort_1 <- mean(data_cohort_1$adjusted_spell_rate)
sd_rate_cohort_1 <- sd(data_cohort_1$adjusted_spell_rate)
data_cohort_2 <-
adjusted_rate_sub_cohorts |>
filter(id_clean == {{cohort_2}},
year == 2023)
mean_rate_cohort_2 <- mean(data_cohort_2$adjusted_spell_rate)
sd_rate_cohort_2 <- sd(data_cohort_2$adjusted_spell_rate)
# Plot
plot <-
data_cohort_1 |>
mutate(std_from_mean_cohort_1 = (adjusted_spell_rate - mean_rate_cohort_1) / sd_rate_cohort_1) |>
select(1:2, adjusted_spell_rate, std_from_mean_cohort_1) |>
rename(cohort_1_adj_rate = adjusted_spell_rate) |>
left_join(data_cohort_2 |>
mutate(std_from_mean_cohort_2 = (adjusted_spell_rate - mean_rate_cohort_2) / sd_rate_cohort_2) |>
select(1:2, adjusted_spell_rate, std_from_mean_cohort_2) |>
rename(cohort_2_adj_rate = adjusted_spell_rate),
by = c("icb23cd", "icb_name_short")) |>
rename(ICB = icb_name_short) |>
mutate(fill_text =
case_when(
(std_from_mean_cohort_1 <= 1 & std_from_mean_cohort_1 >= -1) &
(std_from_mean_cohort_2 <= 1 & std_from_mean_cohort_2 >= -1) ~ "A. Within 1 SD",
(std_from_mean_cohort_1 > 1 & std_from_mean_cohort_2 > 1) ~ "B. Above 1 SD",
(std_from_mean_cohort_1 < -1 & std_from_mean_cohort_2 < -1) ~ "C. Below 1 SD",
TRUE ~ "D. +/- 1 SD on one axis"
)) |>
ggplot(aes(x = cohort_1_adj_rate, y = cohort_2_adj_rate,
colour = fill_text, alpha = fill_text,
label = ICB
)) +
geom_point(size = 3) +
# Cohort 1 lines
geom_vline(xintercept = mean_rate_cohort_1, color = "blue", linetype = "dashed", linewidth = 0.3) +
geom_vline(xintercept = mean_rate_cohort_1 + sd_rate_cohort_1, color = "red", linetype = "dotted", linewidth = 0.25) +
geom_vline(xintercept = mean_rate_cohort_1 - sd_rate_cohort_1, color = "red", linetype = "dotted", linewidth = 0.25) +
# Cohort 2 line
geom_hline(yintercept = mean_rate_cohort_2, color = "blue", linetype = "dashed", linewidth = 0.3) +
geom_hline(yintercept = mean_rate_cohort_2 + sd_rate_cohort_2, color = "red", linetype = "dotted", linewidth = 0.25) +
geom_hline(yintercept = mean_rate_cohort_2 - sd_rate_cohort_2, color = "red", linetype = "dotted", linewidth = 0.25) +
scale_x_continuous(labels = scales::comma) +
scale_alpha_manual(values = c(0.3, 1, 1, 1)) + # Only shade out those within 1 SD on both axis
scale_color_SU() +
theme_SU() +
labs(x = paste0("Admission rate: ", cohort_1_axis),
y = paste0("Admission rate: ", cohort_2_axis),
colour = "",
alpha = ""
)
#plot
ggplotly(plot, tooltip = "label") |>
layout(
title = list(
text = "<b>Variation in admission rates by ICB</b><br>",
x = 0.05, # Center the title
y = 0.95,
xanchor = "left",
font = list(size = 14) # Title font size
),
annotations = list(
list(
text = "<i>Comparison of adjusted admission rates by sub-cohort</i>",
x = -0.01, # Center the title
y = 0.98,
xanchor = "left",
xref = "paper",
yref = "paper",
showarrow = FALSE,
font = list(size = 12) # Subtitle font size
)
)
)
}
# Overlap in cohorts ----
overlap_data <-
aggregate_data %>%
filter(year(month) == 2023) |>
mutate(flag_falls =
case_when(
!is.na(flag_falls_exp) ~ flag_falls_exp,
!is.na(flag_fall_imp_frac) ~ flag_fall_imp_frac,
!is.na(flag_fall_imp_tend) ~ flag_fall_imp_tend,
TRUE ~ NA
)) |>
group_by(flag_frail, flag_elderly_emergency, flag_eol, flag_falls) |>
summarise(spells = sum(spells)) |>
mutate(
flag_frail = !is.na(flag_frail),
flag_eol = !is.na(flag_eol),
flag_falls = !is.na(flag_falls),
flag_elderly_emergency = !is.na(flag_elderly_emergency)
) # Convert flags to logical values
# Calculate the number of spells for each combination
overlap_combinations <-
overlap_data %>%
group_by(flag_frail, flag_elderly_emergency, flag_eol, flag_falls) %>%
summarise(spells = sum(spells), .groups = 'drop')
expanded_data <-
overlap_combinations %>%
rowwise() %>%
do(data.frame(flag_frail = rep(.$flag_frail, .$spells),
flag_eol = rep(.$flag_eol, .$spells),
flag_falls = rep(.$flag_falls, .$spells),
flag_elderly_emergency = rep(.$flag_elderly_emergency, .$spells)
))
# Convert to matrix
expanded_matrix <- as.matrix(expanded_data)
# Create a list for Venn diagram
venn_data <- list(
Frail = which(expanded_matrix[, "flag_frail"]),
EOL = which(expanded_matrix[, "flag_eol"]),
Falls = which(expanded_matrix[, "flag_falls"]),
`Emergency elderly` = which(expanded_matrix[, "flag_elderly_emergency"])
)
# ICB spell denominators ----
icb_spell_denominators <-
read_csv("icb_spell_denominators.csv") |>
clean_names()
spell_proportion <- function(data, label_input) {
data |>
group_by(der_activity_month) |>
summarise(cohort_spells = sum(spells)) |>
left_join(icb_spell_denominators |>
group_by(der_activity_month) |>
summarise(denom_spells = sum(spells)),
by = c("der_activity_month")) |>
mutate(prop = round(cohort_spells/denom_spells * 100, 3)) |>
mutate(month =
as.Date(
paste0(str_sub(der_activity_month,1,4),
"-",
str_sub(der_activity_month,5,6),
"-01")
)
) |>
mutate(id = label_input) |>
select(month, cohort_spells, denom_spells, prop, id)
}
# Patient characteristics ----
patchwork_function <- function(data, title_text) {
# Plot 1
plot_1 <-
data %>%
drop_na(age_range) %>%
filter(year == 2023,
!age_range %in% c("100-104","105-109")) %>%
group_by(age_range, sex) %>%
summarise(pts = sum(person_n)) |>
mutate(pts_2 =
case_when(sex == 1 ~ 0-pts,
TRUE ~ pts)) |>
mutate(sex =
case_when(sex == 1 ~ "Male",
TRUE ~ "Female")) %>%
ggplot(aes(x = pts_2, y = age_range, fill = sex)) +
geom_col() +
geom_vline(xintercept = 0) +
scale_fill_SU() +
scale_x_continuous(labels = function(x) scales::comma(abs(x))) +
theme(legend.position = "bottom",
plot.subtitle = element_text(hjust = 0.5)
) +
labs(x = "Patients",
y = "Age-range",
fill = "Sex:",
subtitle = "Age and sex distribution",
)
# Plot 2
ethnicity_imd <-
data |>
drop_na(age_range) %>%
filter(year == 2023,
!age_range %in% c("100-104","105-109")) %>%
mutate(ethnic_group = str_sub(ethnic_group, 1,1)) %>%
left_join(ethnicity_lookup, by = c("ethnic_group" = "Code")) |>
group_by(Description, imd_decile) |>
summarise(person_n = sum(person_n)) |>
ungroup()
# Reshape the data for the heatmap
heatmap_data <- dcast(ethnicity_imd, Description ~ imd_decile, value.var = "person_n")
# Convert the data to a matrix
heatmap_matrix <- as.matrix(heatmap_data[,-1])
rownames(heatmap_matrix) <- heatmap_data$ethnic_group
plot_2 <-
ethnicity_imd |>
group_by(Description) |>
drop_na(Description) |>
mutate(prop = person_n/sum(person_n) * 100) |>
ggplot(aes(x = factor(imd_decile), y = Description, fill = prop)) +
geom_tile(alpha = 0.9) +
scale_fill_gradient(low = "#686f73", high = "#f9bf07") +
theme(legend.position = "bottom",
plot.subtitle = element_text(hjust = 0.5)
) +
labs(x = "IMD Decile",
y = "Ethnic Group",
subtitle = "IMD distribution in patient ethnicity groups",
fill = "Proportion (%)"
)
plot_1 + plot_2 +
plot_annotation(title = paste0("Sub-cohort demographics - ", title_text),
subtitle = "Mitigable SUS admissions | 2023")
}
# Top diagnoses by cohort
read_diagnosis_list <- function(cohort) {
data <-
read_csv(paste0("top_diagnoses/", cohort, ".csv")) |>
clean_names() |>
select(4,2) |>
rename(Admissions = 2) |>
arrange(desc(Admissions)) |>
mutate(Proportion = round(Admissions/sum(Admissions)*100, 2)) |>
rename(`Primary diagnosis` = icd10_l4_desc) |>
head(10) |>
mutate(Admissions = scales::comma(Admissions))
data
}
# Top diagnoses by cohort
read_procedures_list <- function(cohort) {
data <-
read_csv(paste0("top_procedures/", cohort, ".csv")) |>
clean_names() |>
select(4,2) |>
rename(Admissions = 2) |>
arrange(desc(Admissions)) |>
mutate(Proportion = round(Admissions/sum(Admissions)*100, 2)) |>
rename(`Primary procedure` = opcs_l4_desc) |>
head(10) |>
mutate(Admissions = scales::comma(Admissions))
data
}
```
# Project specifications
::: {.callout-note icon="false"}
## Ask
Size and describe patient cohorts and activity in the inpatient acute settings using National NHP model mitigators.
Generate descriptive analysis to support onward analysis by NHSE analysts covering:
- Number of patients,
- Levels of activity,
- Variation across the country,
- Characteristics of patients
:::
# Outline
::: panel-tabset
## 1. Patient characteristics
Describe the underlying patient demographics within out mitigable-activity sub-cohorts by:
- Age and sex
- Ethnicity and deprivation
## 2. Size and describe
Present activity totals and time-series trends for the combined mitigable-activity cohort and mitigator sub-cohorts.
Measures include:
- Counts of patients, admissions and bed days:
- In combined mitigable-activity cohort
- By mitigator sub-cohorts
- By ICB
- Cohort activity as a share of all admissions
## 3. Use variation
Explore variation in age- and sex-adjusted admission rates to:
- Examine the range of activity by ICB
- Assess whether systems in place are particularly good or bad at treating mitigable activity
**Additional analysis:** Incorporate underlying population need and/or disease prevalence (weighting by deprivation or regression controlling for population variables)
Apply survival analysis techniques to assess differences in care outcomes by patient groups and ICBs. Care outcomes include:
- Readmission post-acute inpatient care
- Motality post-acute inpatient care
**Additional analysis:**
- Summary of care services/types that patients from mitigable cohorts are in contact with in the year prior to death.
- Comparison of location of death in mitigable patients that recieved acute inpatient care in the year prior to death.
## 4. Mitigator overlap
Display the overlap of patients in mitigable cohorts by combined and sub-cohorts.
Outputs include:
- Underlying SQL queries
- Code
- Data extract
- Quarto report output
## 5. Additional deliverable(s)
Ranked table of activity in each mitigator with activity counts and proportion of activity
:::
<hr style="border-top: 2px solid #f9bf07">
# Cohort definition
In keeping with the wider context of this work, we have recreated mitigable activity cohorts used elsewhere in the New Hospital Programme (NHP) Demand and Capacity Model. Our extracts differ primarily in datasource, where the NHP model is built using Hosptial Episode Data (HES) while we have accessed Secondary Uses Service (SUS) data via the National Commissioning Data Repository (NCDR) portal. As such, we have included data between April 2018 and August 2024 and include activity from across England.
Full SQL queries used to define our patient cohorts can be found on the project github repository: [sql_queries](https://github.com/The-Strategy-Unit/Community_Strategies/tree/main/sql).
Details of the original NHP queries can be found here: [NHP mitigators](https://connect.strategyunitwm.nhs.uk/nhp/project_information/modelling_methodology/activity_mitigators/inpatient_activity_mitigators.html).
::: panel-tabset
### Emergency elderly
Admissions included in our emergency elderly cohort are all emergency admissions in patients aged 75 and older (Admission_Method LIKE "2%" - details [here](https://www.datadictionary.nhs.uk/attributes/admission_method.html)).
### Frail
Admissions included in our Frail cohort are all emergency admissions in patients aged 65 and older that include a Spell_Primary_Diagnosis code indicating frailty as the cause of the admission. This is different to the NHP frailty definition which focuses only on patients aged 75 years and older.
::: {.callout-caution collapse="true"}
## Expand To view ICD10 frailty diagnosis codes:
LEFT([Spell_Primary_Diagnosis],3) IN (
'F00','G81','G30','I69','R29','R39','F05','W19',
'S00','R31','B96','R41','R26','I67','R56','R40',
'T83','S06','S42','E87','M25','E86','R54','Z50',
'F03','W18','Z75','F01','S80','L03','H54','E53',
'Z60','G20','R55','S22','K59','N17','L89','Z22',
'B95','L97','R44','K26','I95','N19','A41','Z87',
'J96','X59','M19','G40','M81','S72','S32','E16',
'R94','N18','R33','R69','N28','R32','G31','Y95',
'S09','R45','G45','Z74','M79','W06','S01','A04',
'A09','J18','J69','R47','E55','Z93','R02','R63',
'H91','W10','W01','E05','M41','R13','Z99','U80',
'M80','K92','I63','N20','F10','Y84','R00','J22',
'Z73','R79','Z91','S51','F32','M48','E83','M15',
'D64','L08','R11','K52','R50'
)
:::
### Falls
Our falls cohort included any patient aged 65 years or older that had an emergency admission and a primary diagnosis indicating a fall (expliticly or implicitly).
::: {.callout-caution collapse="true"}
## Expand To view ICD10 falls diagnosis codes:
**Explicit**:
Spell_Primary_Diagnosis LIKE 'W[01][0-9]%'
**Implicit - fractures**:
(
Spell_Primary_Diagnosis LIKE 'M48[45]%'
OR
Spell_Primary_Diagnosis LIKE 'M80[0-589]%'
OR
Spell_Primary_Diagnosis LIKE 'S22[01]%'
OR
Spell_Primary_Diagnosis LIKE 'S32[0-47]%'
OR
Spell_Primary_Diagnosis LIKE 'S42[234]%'
OR
Spell_Primary_Diagnosis LIKE 'S52%'
OR
Spell_Primary_Diagnosis LIKE 'S620%'
OR
Spell_Primary_Diagnosis LIKE 'S72[0-48]%'
OR
Spell_Primary_Diagnosis LIKE 'T08X%'
)
AND
Spell_Primary_Diagnosis NOT LIKE '[VWXY]%'
**Implicit - Tendency to fall**:
Spell_Primary_Diagnosis LIKE 'R296%'
:::
### End of life
End of life spells were identified by filtering admissions on Dischare_Method = 4 (Outcome - Patient died. Details [here](https://www.datadictionary.nhs.uk/data_elements/discharge_method_code__hospital_provider_spell_.html)) where the length of stay (Der_Spell_LoS) was less than 14 days and no procedure was undertaken (Der_Procedure_All IS NULL).
:::
<hr style="border-top: 2px solid #f9bf07">
# Patient characteristics
## Demographics
In both our emergency elderly and frail patient groups, it is apparent that within the Black and Asian ethnic groups, the majority of patients are clustered in the most deprived IMD deciles (particularly deciles 2-4). However, when considering emergency elderly admissions, in larger group of White British patients, the proportion of patients gradually increases with affluence.
::: panel-tabset
### Emergency elderly
```{r}
patchwork_function(aggregate_data_elderly_emergency, "Emergency elderly patients")
```
### Frail
```{r}
patchwork_function(aggregate_data_frail, "Frail patients")
```
### Falls
```{r}
patchwork_function(aggregate_data_falls, "Falls patients")
```
### End-of-life
```{r}
patchwork_function(aggregate_data_eol, "End-of-life patients")
```
:::
## Most frequent diagnoses
::: panel-tabset
### Emergency elderly
```{r}
create_dt(read_diagnosis_list("frail"))