This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.R
1760 lines (1548 loc) · 60.6 KB
/
pipeline.R
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
# pipeline.R -------------------------------------------------------------------
# This script is used to run the RAP for the MUMH quarterly publication
# 1. install required packages -------------------------------------------------
# TODO: investigate using renv package for dependency management
req_pkgs <- c("broom", "data.table", "dbplyr", "dplyr", "DT" , "highcharter", "lubridate",
"logr", "openxlsx", "rmarkdown", "rsample", "stringr", "tidyr", "yaml")
# utils::install.packages(req_pkgs, dependencies = TRUE)
# # #
# devtools::install_github(
# "nhsbsa-data-analytics/mumhquarterly",
# auth_token = Sys.getenv("GITHUB_PAT")
# )
# #
# devtools::install_github("nhsbsa-data-analytics/nhsbsaR")
invisible(lapply(c(req_pkgs, "mumhquarterly", "nhsbsaR"), library, character.only = TRUE))
# 2. set options ---------------------------------------------------------------
mumhquarterly::mumh_options()
# 3. load most recent data and add 3 months to max date ------------------------
# get most recent monthly file
recent_file_monthly <- rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "monthly"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "monthly"
)
)$mtime)]
# read data
recent_data_monthly <- data.table::fread(recent_file_monthly,
keepLeadingZeros = TRUE)
# get most recent quarterly file
recent_file_quarterly <- rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "quarterly"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "quarterly"
)
)$mtime)]
# read data
recent_data_quarterly <- data.table::fread(recent_file_quarterly,
keepLeadingZeros = TRUE)
# get most recent monthly model data file
recent_file_model <- rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "model"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "model"
)
)$mtime)]
# read data
recent_data_model <- data.table::fread(recent_file_model,
keepLeadingZeros = TRUE)
# get max month
max_month <- as.Date(
paste0(
max(
recent_data_monthly$YEAR_MONTH
),
"01"
),
format = "%Y%m%d"
)
# get max month plus one
max_month_plus <- as.Date(paste0(max(recent_data_monthly$YEAR_MONTH),
"01"),
format = "%Y%m%d") %m+% months(1)
# convert to DW format
max_month_plus_dw <- as.numeric(paste0(format(max_month_plus,
"%Y"),
format(max_month_plus,
"%m")))
# 4. extract data from NHSBSA Data Warehouse -----------------------------------
# build connection to database
con <- con_nhsbsa(
dsn = "FBS_8192k",
driver = "Oracle in OraClient19Home1",
"DWCP",
username = rstudioapi::showPrompt(title = "Username", message = "Username"),
password = rstudioapi::askForPassword()
)
# get max month available in DWH
ym_dim <- dplyr::tbl(con,
from = dbplyr::in_schema("DIM", "YEAR_MONTH_DIM")) %>%
# shrink table to remove unnecessary data
dplyr::filter(
YEAR_MONTH >= 201401L,
YEAR_MONTH <= dplyr::sql(
"MGMT.PKG_PUBLIC_DWH_FUNCTIONS.f_get_latest_period('EPACT2')"
)
) %>%
dplyr::select(YEAR_MONTH,
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
FINANCIAL_QUARTER_EXT) %>%
# add month counts for financial quarters and financial years to latest
# complete periods
dplyr::mutate(
# create our own financial quarter column that max/min and sort operations
# will work on
FINANCIAL_QUARTER_NM = dplyr::sql("FINANCIAL_YEAR||' Q'||FINANCIAL_QUARTER"),
# window function to perform counts within groups
Q_COUNT = dbplyr::win_over(
expr = dplyr::sql("count(distinct YEAR_MONTH)"),
partition = "FINANCIAL_QUARTER_EXT",
con = con
),
FY_COUNT = dbplyr::win_over(
expr = dplyr::sql("count(distinct YEAR_MONTH)"),
partition = "FINANCIAL_YEAR",
con = con
)
)
# extract latest available full financial quarter
ltst_month <- ym_dim %>%
dplyr::filter(Q_COUNT == 3) %>%
dplyr::select(YEAR_MONTH, FINANCIAL_QUARTER_EXT, FINANCIAL_QUARTER_NM) %>%
dplyr::filter(YEAR_MONTH == max(YEAR_MONTH, na.rm = TRUE)) %>%
dplyr::distinct() %>%
dplyr::pull(YEAR_MONTH)
# get max month in dwh
max_month_dw <- as.Date(paste0(ltst_month,
"01"),
format = "%Y%m%d")
# create table names
time_table <- paste0("MUMH_MONTH_TDIM_", as.character(ltst_month))
porg_table <- paste0("MUMH_MONTH_PORG_DIM_", as.character(ltst_month))
drug_table <- paste0("MUMH_MONTH_DRUG_DIM_", as.character(ltst_month))
# only get new data if max month in dwh is greater than that in most recent data
if(max_month_dw <= max_month) {
print("No new quarterly data available in the Data Warehouse, will use most recent saved data.")
DBI::dbDisconnect(con)
} else {
# build time dimension table in schema
# drop time dimension if exists
exists <- con %>%
DBI::dbExistsTable(name = time_table)
# Drop any existing table beforehand
if (exists) {
con %>%
DBI::dbRemoveTable(name = time_table)
}
# build table
# this will create a new table of all data, so table will be large
create_tdim(con) %>%
compute(time_table, analyze = FALSE, temporary = FALSE)
# if only getting new data for each quarterly publication use commented code below
# and append to previous data from shared area
#create_tdim(con, start = max_month_plus_dw) %>%
#compute(time_table, analyze = FALSE, temporary = FALSE)
# build org dimension table in schema
# drop org dimension if exists
exists <- con %>%
DBI::dbExistsTable(name = porg_table)
# Drop any existing table beforehand
if (exists) {
con %>%
DBI::dbRemoveTable(name = porg_table)
}
# build table
create_org_dim(con, country = 1) %>%
compute(porg_table, analyze = FALSE, temporary = FALSE)
# build drug dimension table in schema
# drop drug dimension if exists
exists <- con %>%
DBI::dbExistsTable(name = drug_table)
# Drop any existing table beforehand
if (exists) {
con %>%
DBI::dbRemoveTable(name = drug_table)
}
# build table
create_drug_dim(con, bnf_codes = c("0401", "0402", "0403", "0404", "0411")) %>%
compute(drug_table, analyze = FALSE, temporary = FALSE)
# build table
age <- dplyr::tbl(con,
from = dbplyr::in_schema("DIM", "AGE_DIM")) %>%
select(AGE,
DALL_5YR_BAND)
# create fact table
fact <- create_fact(con)
# drop raw data if exists
exists <- con %>%
DBI::dbExistsTable(name = "MUMH_RAW_DATA")
# Drop any existing table beforehand
if (exists) {
con %>%
DBI::dbRemoveTable(name = "MUMH_RAW_DATA")
}
## create raw data in schema
fact %>%
inner_join(tbl(con, time_table) , by = "YEAR_MONTH") %>%
inner_join(tbl(con, porg_table) , by = c("PRESC_TYPE_PRNT" = "LVL_5_OUPDT",
"PRESC_ID_PRNT" = "LVL_5_OU")) %>%
inner_join(tbl(con, drug_table), by = c("CALC_PREC_DRUG_RECORD_ID" = "RECORD_ID",
"YEAR_MONTH" = "YEAR_MONTH")) %>%
inner_join(age,
by = c("CALC_AGE" = "AGE")) %>%
compute("MUMH_RAW_DATA", analyze = FALSE, temporary = FALSE)
## build and collect quarterly data
mumh_quarterly <- tbl(con, "MUMH_RAW_DATA") %>%
group_by(
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
IDENTIFIED_PATIENT_ID,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG
) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC) / 100
) %>%
mutate(PATIENT_COUNT = case_when(IDENTIFIED_FLAG == "Y" ~ 1,
IDENTIFIED_FLAG == "N" ~ 0)) %>%
ungroup() %>%
group_by(FINANCIAL_YEAR,
FINANCIAL_QUARTER,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
PATIENT_COUNT = sum(PATIENT_COUNT)
) %>%
rename(SECTION_NAME = SECTION_DESCR,
SECTION_CODE = BNF_SECTION) %>%
arrange(FINANCIAL_YEAR,
FINANCIAL_QUARTER,
SECTION_CODE,
desc(IDENTIFIED_FLAG)) %>%
collect
## build and collect monthly data
mumh_monthly <- tbl(con, "MUMH_RAW_DATA") %>%
group_by(
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
YEAR_MONTH,
IDENTIFIED_PATIENT_ID,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG
) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC) / 100
) %>%
mutate(PATIENT_COUNT = case_when(IDENTIFIED_FLAG == "Y" ~ 1,
IDENTIFIED_FLAG == "N" ~ 0)) %>%
ungroup() %>%
group_by(
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
YEAR_MONTH,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG
) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
PATIENT_COUNT = sum(PATIENT_COUNT)
) %>%
rename(SECTION_NAME = SECTION_DESCR,
SECTION_CODE = BNF_SECTION) %>%
arrange(YEAR_MONTH, SECTION_CODE, desc(IDENTIFIED_FLAG)) %>%
collect
## build and collect model data
mumh_model <- tbl(con, "MUMH_RAW_DATA") %>%
mutate(
PDS_GENDER = case_when(PDS_GENDER == 1 ~ "M",
PDS_GENDER == 2 ~ "F",
TRUE ~ "U"),
DALL_5YR_BAND = case_when(is.na(DALL_5YR_BAND) ~ "Unknown",
TRUE ~ DALL_5YR_BAND)
) %>%
group_by(
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
YEAR_MONTH,
IDENTIFIED_PATIENT_ID,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG,
PDS_GENDER,
DALL_5YR_BAND
) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC) / 100
) %>%
mutate(PATIENT_COUNT = case_when(IDENTIFIED_FLAG == "Y" ~ 1,
IDENTIFIED_FLAG == "N" ~ 0)) %>%
ungroup() %>%
group_by(
FINANCIAL_YEAR,
FINANCIAL_QUARTER,
YEAR_MONTH,
SECTION_DESCR,
BNF_SECTION,
IDENTIFIED_FLAG,
PDS_GENDER,
DALL_5YR_BAND,
) %>%
summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
PATIENT_COUNT = sum(PATIENT_COUNT)
) %>%
rename(SECTION_NAME = SECTION_DESCR,
SECTION_CODE = BNF_SECTION) %>%
arrange(YEAR_MONTH, SECTION_CODE, desc(IDENTIFIED_FLAG)) %>%
collect
DBI::dbDisconnect(con)
# if only getting new data for each quarterly publication
# join any new data to most recent saved data
#mumh_monthly <- recent_data_monthly %>%
#bind_rows(mumh_monthly)
#mumh_quarterly <- recent_data_quarterly %>%
#bind_rows(mumh_quarterly)
#mumh_model <- recent_data_model %>%
#bind_rows(mumh_model)
save_data(mumh_quarterly, dir = "Y:/Official Stats/MUMH", filename = "mumh_quarterly")
save_data(mumh_monthly, dir = "Y:/Official Stats/MUMH", filename = "mumh_monthly")
save_data(mumh_model, dir = "Y:/Official Stats/MUMH", filename = "mumh_model")
}
# 5. import data ---------------------------------------------------------------
# import data from data folder to perform aggregations etc without having to
# maintain connection to DWH
raw_data <- list()
# read most recent monthly file
raw_data$monthly <- data.table::fread(rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "monthly"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "monthly"
)
)$mtime)],
keepLeadingZeros = TRUE)
# read most recent quarterly file
raw_data$quarterly <- data.table::fread(rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "quarterly"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "quarterly"
)
)$mtime)],
keepLeadingZeros = TRUE)
# read most recent model data file
raw_data$model_data <- data.table::fread(rownames(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "model"
)
))[which.max(file.info(
list.files(
"Y:/Official Stats/MUMH/data",
full.names = T,
pattern = "model"
)
)$mtime)],
keepLeadingZeros = TRUE)
# calculate dispensing days for use in covid model
# use latest year of current financial year, eg. 2023 for financial year 2022/23
dispensing_days <- mumhquarterly::get_dispensing_days(2023)
# 6. data manipulation ---------------------------------------------------------
# patient identification rates for most recent data
period <- raw_data$quarterly %>%
dplyr::select(FINANCIAL_QUARTER) %>%
dplyr::distinct() %>%
dplyr::slice_max(FINANCIAL_QUARTER,
n = 4) %>%
dplyr::pull()
# create dataframe
patient_identification <- raw_data$quarterly %>%
dplyr::filter(FINANCIAL_QUARTER %in% period) %>%
tidyr::pivot_wider(
names_from = IDENTIFIED_FLAG,
values_from = c(ITEM_COUNT, ITEM_PAY_DR_NIC, PATIENT_COUNT)
) %>%
dplyr::mutate(RATE = paste0(format(round(
ITEM_COUNT_Y / (ITEM_COUNT_Y + ITEM_COUNT_N) * 100, 1
),
nsmall = 1), "%")) %>%
select(FINANCIAL_QUARTER,
`BNF Section Name` = SECTION_NAME,
`BNF Section Code` = SECTION_CODE,
RATE) %>%
tidyr::pivot_wider(names_from = FINANCIAL_QUARTER,
values_from = RATE) %>%
dplyr::arrange(`BNF Section Code`)
# chart data for use in markdown
chart_data<- list()
chart_data$monthly <- raw_data$monthly %>%
dplyr::group_by(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE) %>%
dplyr::summarise(
ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
PATIENT_COUNT = sum(PATIENT_COUNT),
.groups = "drop"
) %>%
dplyr::group_by(SECTION_NAME, SECTION_CODE) %>%
dplyr::mutate(
MONTH_INDEX = dplyr::row_number(),
MONTH_START = as.Date(paste0(YEAR_MONTH, "01"), format = "%Y%m%d"),
MONTH_NUM = lubridate::month(MONTH_START)
) %>%
dplyr::left_join(dispensing_days,
by = "YEAR_MONTH") %>%
dplyr::ungroup()
# model data using old version of covid model for use in model testing
# filter monthly raw data to identified patients only
# join monthly raw data to dispensing days to allow modelling
model_data_old <- raw_data$monthly %>%
dplyr::group_by(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE) %>%
dplyr::summarise(ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC)) %>%
dplyr::group_by(SECTION_NAME, SECTION_CODE) %>%
dplyr::mutate(
MONTH_INDEX = dplyr::row_number(),
MONTH_START = as.Date(paste0(YEAR_MONTH, "01"), format = "%Y%m%d"),
MONTH_NUM = lubridate::month(MONTH_START)
) %>%
dplyr::left_join(dispensing_days,
by = "YEAR_MONTH") %>%
dplyr::ungroup()
# 7. write data to .xlsx -------------------------------------------------------
# Text referencing time periods in sheet titles and notes needs to be manually updated
# for example 'April 2015 to December 2022' is the time period for current publication
# To do: automate time periods in file and sheet titles and notes
# create dataframe for full patient identification
patient_identification_excel <- raw_data$quarterly %>%
tidyr::pivot_wider(
names_from = IDENTIFIED_FLAG,
values_from = c(ITEM_COUNT, ITEM_PAY_DR_NIC, PATIENT_COUNT)
) %>%
dplyr::mutate(RATE = round(ITEM_COUNT_Y / (ITEM_COUNT_Y + ITEM_COUNT_N) * 100, 10)) %>%
select(FINANCIAL_QUARTER,
`BNF Section Name` = SECTION_NAME,
`BNF Section Code` = SECTION_CODE,
RATE) %>%
tidyr::pivot_wider(names_from = FINANCIAL_QUARTER,
values_from = RATE) %>%
dplyr::arrange(`BNF Section Code`)
# create wb object
# create list of sheetnames needed (overview and metadata created automatically)
sheetNames <- c("Patient_Identification",
"Monthly_Data",
"Quarterly_Data")
wb <- mumhquarterly::create_wb(sheetNames)
# create metadata tab (will need to open file to auto adjust some row height once ran)
meta_fields <- c(
"BNF Section Code",
"BNF Section Name",
"Financial Year",
"Year Month",
"Financial Quarter",
"Identified Patient",
"Total Items",
"Total Net Ingredient Cost (GBP)",
"Total Patients"
)
meta_descs <-
c(
"The unique code used to refer to the British National Formulary (BNF) section.",
"The name given to a British National Formulary (BNF) section. This is the next broadest grouping of the BNF therapeutical classification system after chapter.",
"The financial year to which the data belongs.",
"The year and month to which the data belongs, denoted in YYYYMM format.",
"The financial quarter to which the data belongs.",
"This shows where an item has been attributed to an NHS number that has been verified by the Personal Demographics Service (PDS).",
"The number of prescription items dispensed. 'Items' is the number of times a product appears on a prescription form. Prescription forms include both paper prescriptions and electronic messages.",
"Total Net Ingredient Cost is the amount that would be paid using the basic price of the prescribed drug or appliance and the quantity prescribed. Sometimes called the 'Net Ingredient Cost' (NIC). The basic price is given either in the Drug Tariff or is determined from prices published by manufacturers, wholesalers or suppliers. Basic price is set out in Parts 8 and 9 of the Drug Tariff. For any drugs or appliances not in Part 8, the price is usually taken from the manufacturer, wholesaler or supplier of the product. This is given in GBP (£).",
"Where patients are identified via the flag, the number of patients that the data corresponds to. This will always be 0 where 'Identified Patient' = N."
)
mumhquarterly::create_metadata(wb,
meta_fields,
meta_descs
)
#### Patient identification
# write data to sheet
mumhquarterly::write_sheet(
wb,
"Patient_Identification",
"Medicines Used in Mental Health - Quarterly Summary Statistics April 2015 to December 2022 - Proportion of items for which an NHS number was recorded (%)",
c(
"The below proportions reflect the percentage of prescription items where a PDS verified NHS number was recorded."
),
patient_identification_excel,
42
)
# left align text/character columns A and B
mumhquarterly::format_data(wb,
"Patient_Identification",
c("A", "B"),
"left",
"")
# right align columns and round to 2 decimal places for numerical columns C to AG
# column letter references will need to be updated whenever more data added
mumhquarterly::format_data(wb,
"Patient_Identification",
c("C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"AA", "AB", "AC", "AD", "AE", "AF", "AG"),
"right",
"0.00")
#### Monthly data
# write data to sheet
mumhquarterly::write_sheet(
wb,
"Monthly_Data",
"Medicines Used in Mental Health - Quarterly Summary Statistics April 2015 to December 2022 totals by year month",
c(
"1. Field definitions can be found on the 'Metadata' tab.",
"2. Patient counts should not be aggregated to any other level than that which is displayed to prevent multiple counting of patients."
),
raw_data$monthly %>%
rename(
`Financal Year` = FINANCIAL_YEAR,
`Financial Quarter` = FINANCIAL_QUARTER,
`Year Month` = YEAR_MONTH,
`BNF Section Name` = SECTION_NAME,
`BNF Section Code` = SECTION_CODE,
`Identified Patient` = IDENTIFIED_FLAG,
`Total Patients` = PATIENT_COUNT,
`Total Items` = ITEM_COUNT,
`Total Net Ingredient Cost (GBP)` = ITEM_PAY_DR_NIC
) %>%
select(
`Financal Year`,
`Financial Quarter`,
`Year Month`,
`BNF Section Name`,
`BNF Section Code`,
`Identified Patient`,
`Total Patients`,
`Total Items`,
`Total Net Ingredient Cost (GBP)`
),
14
)
# left align columns A to F
mumhquarterly::format_data(wb,
"Monthly_Data",
c("A", "B", "C", "D", "E", "F"),
"left",
"")
# right align columns G and H and round to whole numbers with thousand separator
mumhquarterly::format_data(wb,
"Monthly_Data",
c("G", "H"),
"right",
"#,##0")
# right align column I and round to 2 decimal places with thousand separator
mumhquarterly::format_data(wb,
"Monthly_Data",
c("I"),
"right",
"#,##0.00")
#### Quarterly data
# write data to sheet
mumhquarterly::write_sheet(
wb,
"Quarterly_Data",
"Medicines Used in Mental Health - Quarterly Summary Statistics April 2015 to December 2022 totals by quarter",
c(
"1. Field definitions can be found on the 'Metadata' tab.",
"2. Patient counts should not be aggregated to any other level than that which is displayed to prevent multiple counting of patients."
),
raw_data$quarterly %>%
rename(
`Financal Year` = FINANCIAL_YEAR,
`Financial Quarter` = FINANCIAL_QUARTER,
`BNF Section Name` = SECTION_NAME,
`BNF Section Code` = SECTION_CODE,
`Identified Patient` = IDENTIFIED_FLAG,
`Total Patients` = PATIENT_COUNT,
`Total Items` = ITEM_COUNT,
`Total Net Ingredient Cost (GBP)` = ITEM_PAY_DR_NIC
) %>%
select(
`Financal Year`,
`Financial Quarter`,
`BNF Section Name`,
`BNF Section Code`,
`Identified Patient`,
`Total Patients`,
`Total Items`,
`Total Net Ingredient Cost (GBP)`
),
14
)
# left align columns A to F
mumhquarterly::format_data(wb,
"Quarterly_Data",
c("A", "B", "C", "D", "E"),
"left",
"")
# right align columns G and H and round to whole numbers with thousand separator
mumhquarterly::format_data(wb,
"Quarterly_Data",
c("F", "G"),
"right",
"#,##0")
# right align column I and round to 2 decimal places with thousand separator
mumhquarterly::format_data(wb,
"Quarterly_Data",
c("H"),
"right",
"#,##0.00")
# save file into outputs folder
# file name will need to be updated to new time period for each new publication
openxlsx::saveWorkbook(wb,
"outputs/mumh_quarterly_dec22_v001.xlsx",
overwrite = TRUE)
# 8. Covid model figures -------------------------------------------------------
# this section builds, tests and implements the new covid model
# using patient ageband and gender data
# To do: turn new covid model back into function to reduce size of code
# join dispensing days to raw data, add columns for position of month in year,
# position of month in full dataset, and month start date
# keep original 5 year agebands and fill rows where ageband has no items recorded
df5 <- raw_data$model_data |>
dplyr::group_by(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER,
DALL_5YR_BAND) |>
dplyr::summarise(ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
.groups = "drop") |>
tidyr::complete(DALL_5YR_BAND,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
tidyr::complete(IDENTIFIED_FLAG,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
DALL_5YR_BAND,
PDS_GENDER),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
tidyr::complete(PDS_GENDER,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
DALL_5YR_BAND),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
dplyr::group_by(SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER,
DALL_5YR_BAND) |>
dplyr::group_by(SECTION_NAME, SECTION_CODE, IDENTIFIED_FLAG,
PDS_GENDER, DALL_5YR_BAND) |>
dplyr::mutate(
MONTH_START = as.Date(paste0(YEAR_MONTH, "01"), format = "%Y%m%d"),
MONTH_NUM = lubridate::month(MONTH_START),
MONTH_INDEX = lubridate::interval(lubridate::dmy(01032015), as.Date(MONTH_START)) %/% months(1)
) |>
dplyr::left_join(dispensing_days,
by = "YEAR_MONTH") |>
dplyr::filter(!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "F"),
!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "M"),
!(PDS_GENDER == "U" | DALL_5YR_BAND == "Unknown")) %>%
dplyr::ungroup()
# repeat to create dataset with 20 year agebands instead of 5 year
# only keep observations with known age and gender
# and fill rows where ageband has no items recorded
df20 <- raw_data$model |>
dplyr::mutate(BAND_20YR = dplyr::case_when(DALL_5YR_BAND %in% c("00-04", "05-09", "10-14", "15-19") ~ "00-19",
DALL_5YR_BAND %in% c("20-24", "25-29", "30-34", "35-39") ~ "20-39",
DALL_5YR_BAND %in% c("40-44", "45-49", "50-54", "55-59") ~ "40-59",
DALL_5YR_BAND %in% c("60-64", "65-69", "70-74", "75-79") ~ "60-79",
DALL_5YR_BAND == "Unknown" ~ "Unknown",
TRUE ~ "80+")) |>
dplyr::select(!(DALL_5YR_BAND)) |>
dplyr::group_by(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER,
BAND_20YR) |>
dplyr::summarise(ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC),
.groups = "drop") |>
tidyr::complete(BAND_20YR,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
tidyr::complete(IDENTIFIED_FLAG,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
BAND_20YR,
PDS_GENDER),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
tidyr::complete(PDS_GENDER,
nesting(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
BAND_20YR),
fill = list(ITEM_COUNT = 0,
ITEM_PAY_DR_NIC = 0,
PATIENT_COUNT = 0)) |>
dplyr::group_by(SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER,
BAND_20YR) |>
dplyr::group_by(SECTION_NAME, SECTION_CODE, IDENTIFIED_FLAG,
PDS_GENDER, BAND_20YR) |>
dplyr::mutate(
MONTH_START = as.Date(paste0(YEAR_MONTH, "01"), format = "%Y%m%d"),
MONTH_NUM = lubridate::month(MONTH_START),
MONTH_INDEX = lubridate::interval(lubridate::dmy(01032015), as.Date(MONTH_START)) %/% months(1)
) |>
dplyr::left_join(dispensing_days,
by = "YEAR_MONTH") |>
dplyr::filter(!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "F"),
!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "M"),
!(PDS_GENDER == "U" | BAND_20YR == "Unknown")) %>%
dplyr::ungroup()
# create additional dataset with both agebands for use in variable selection later
df_both <- raw_data$model |>
dplyr::mutate(BAND_20YR = dplyr::case_when(DALL_5YR_BAND %in% c("00-04", "05-09", "10-14", "15-19") ~ "00-19",
DALL_5YR_BAND %in% c("20-24", "25-29", "30-34", "35-39") ~ "20-39",
DALL_5YR_BAND %in% c("40-44", "45-49", "50-54", "55-59") ~ "40-59",
DALL_5YR_BAND %in% c("60-64", "65-69", "70-74", "75-79") ~ "60-79",
DALL_5YR_BAND == "Unknown" ~ "Unknown",
TRUE ~ "80+")) |>
dplyr::group_by(YEAR_MONTH,
SECTION_NAME,
SECTION_CODE,
IDENTIFIED_FLAG,
PDS_GENDER,
DALL_5YR_BAND,
BAND_20YR) |>
dplyr::summarise(ITEM_COUNT = sum(ITEM_COUNT),
ITEM_PAY_DR_NIC = sum(ITEM_PAY_DR_NIC)) |>
dplyr::group_by(SECTION_NAME, SECTION_CODE, IDENTIFIED_FLAG,
PDS_GENDER, BAND_20YR, DALL_5YR_BAND) |>
dplyr::mutate(
MONTH_START = as.Date(paste0(YEAR_MONTH, "01"), format = "%Y%m%d"),
MONTH_NUM = lubridate::month(MONTH_START),
MONTH_INDEX = lubridate::interval(lubridate::dmy(01032015), as.Date(MONTH_START)) %/% months(1)
) |>
dplyr::left_join(dispensing_days,
by = "YEAR_MONTH") |>
dplyr::filter(!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "F"),
!(IDENTIFIED_FLAG == "N" & PDS_GENDER == "M"),
!(PDS_GENDER == "U" | DALL_5YR_BAND == "Unknown" | BAND_20YR == "Unknown")) |>
dplyr::ungroup()
# add columns to separate out months into individual factor variables
# for use in later predictions
df5 <- df5 %>%
dplyr::mutate(
m_01 = 1*(MONTH_NUM == 1),
m_02 = 1*(MONTH_NUM == 2),
m_03 = 1*(MONTH_NUM == 3),
m_04 = 1*(MONTH_NUM == 4),
m_05 = 1*(MONTH_NUM == 5),
m_06 = 1*(MONTH_NUM == 6),
m_07 = 1*(MONTH_NUM == 7),
m_08 = 1*(MONTH_NUM == 8),
m_09 = 1*(MONTH_NUM == 9),
m_10 = 1*(MONTH_NUM == 10),
m_11 = 1*(MONTH_NUM == 11),
m_12 = 1*(MONTH_NUM == 12)
)
# repeat for 20 year ageband data
df20 <- df20 %>%
dplyr::mutate(
m_01 = 1*(MONTH_NUM == 1),
m_02 = 1*(MONTH_NUM == 2),
m_03 = 1*(MONTH_NUM == 3),
m_04 = 1*(MONTH_NUM == 4),
m_05 = 1*(MONTH_NUM == 5),
m_06 = 1*(MONTH_NUM == 6),
m_07 = 1*(MONTH_NUM == 7),
m_08 = 1*(MONTH_NUM == 8),
m_09 = 1*(MONTH_NUM == 9),
m_10 = 1*(MONTH_NUM == 10),
m_11 = 1*(MONTH_NUM == 11),
m_12 = 1*(MONTH_NUM == 12)
)
## Model exploration and fitting
# explore variable selection for use in model
# check if smaller or larger agebands makes a difference
# test and train data for df_both dataset, split by pre-covid trend data and covid data
both_time <- df_both %>%
ungroup() %>%
dplyr::mutate(time_period = case_when(YEAR_MONTH <= 202002 ~ "pre_covid",
TRUE ~ "covid"))
both_split <- rsample::group_initial_split(both_time, time_period)
both_train <- rsample::training(both_split)
both_test <- rsample::testing(both_split)
# build 5yr vs 20yr agebands model for each BNF section using full set of variables
# linear model using lm() function
mod_0401_5 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(DALL_5YR_BAND),
data = filter(both_train, SECTION_CODE == "0401"))
mod_0401_10 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(BAND_20YR),
data = filter(both_train, SECTION_CODE == "0401"))
mod_0402_5 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(DALL_5YR_BAND),
data = filter(both_train, SECTION_CODE == "0402"))
mod_0402_10 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(BAND_20YR),
data = filter(both_train, SECTION_CODE == "0402"))
mod_0403_5 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(DALL_5YR_BAND),
data = filter(both_train, SECTION_CODE == "0403"))
mod_0403_10 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(BAND_20YR),
data = filter(both_train, SECTION_CODE == "0403"))
mod_0404_5 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(DALL_5YR_BAND),
data = filter(both_train, SECTION_CODE == "0404"))
mod_0404_10 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(BAND_20YR),
data = filter(both_train, SECTION_CODE == "0404"))
mod_0411_5 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(DALL_5YR_BAND),
data = filter(both_train, SECTION_CODE == "0411"))
mod_0411_10 <- lm(ITEM_COUNT ~ MONTH_INDEX + DISPENSING_DAYS + as.factor(MONTH_NUM)
+ PDS_GENDER*as.factor(BAND_20YR),
data = filter(both_train, SECTION_CODE == "0411"))
# compare model fits using Akaike Information Criteria (AIC)
# lower AIC is generally considered preferable depending on other considerations
# 5 year band vs 20 year band, 5 year band consistently has lower AIC
broom::glance(mod_0401_5)
broom::glance(mod_0401_10)
broom::glance(mod_0402_5)
broom::glance(mod_0402_10)
broom::glance(mod_0403_5)
broom::glance(mod_0403_10)
broom::glance(mod_0404_5)
broom::glance(mod_0404_10)
broom::glance(mod_0411_5)
broom::glance(mod_0411_10)
# however evidence of overfitting of model, suggests 20 year ageband should be used