-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset_data_aurum_validation_closedloop_final.R
3691 lines (3017 loc) · 150 KB
/
set_data_aurum_validation_closedloop_final.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
# load libraries
rm(list=ls())
require(tidyverse)
library(rms)
library(tableone)
#library(plyr)
library(ggthemes)
library(forestplot)
library(broom)
library(ggplotify)
library(patchwork)
library(scales)
library(forcats)
library(marginaleffects)
output_dir <- "C:/Users/jmd237/OneDrive - University of Exeter/John/Projects/2023_SGLT2DPP4Aurum/results/"
data_dir <- "C:/Users/jmd237/OneDrive - University of Exeter/John/CPRD/mastermind22/"
#### Data prep (run once only) ####
#Adapt from Pedros code (see Projects\2019_SGLT2vsDPP4\scripts\validation\set_data_validation.R)
dataset.type <- "diagnostics"
set_up_data_sglt2_dpp4 <- function(dataset.type) {
##### Input variables
# dataset.type: a character string mentioning the type of dataset required
# initial checks
if (missing(dataset.type)) {stop("'dataset.type' needs to be supplied")}
if (!is.character(dataset.type)) {stop("'dataset.type' must be a character string")}
if (!(dataset.type %in% c("diagnostics", "synthetic", "full.cohort", "ps.model.train", "ps.model.test", "hba1c.train", "hba1c.test", "weight.dataset", "discontinuation.dataset", "egfr.dataset"))) {
stop("'dataset.type' must one of: diagnostics / synthetic / full.cohort / ps.model.train / ps.model.test / hba1c.train / hba1c.test / weight.dataset / discontinuation.dataset / egfr.dataset")
}}
# load original dataset # name - t2d_1stinstance
#load("/slade/CPRD_data/mastermind_2022/20221110_t2d_1stinstance.Rda")
load(paste0(data_dir,"20221212_t2d_1stinstance.Rda"))
cprd <- t2d_1stinstance
##### Select only SGLT-2 and DPP4
#SGLT2 vs DPP4
cprd <- cprd %>%
filter(drugclass == "DPP4" | drugclass == "SGLT2")
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Select only SGLT-2 and GLP-1")
print("################################################")
print(nrow(cprd))
print(table(cprd$drugclass))
}
##### Drop patients initiating before 1/1/2013
# Explore adjusted HbA1c repsonse by calendar year
cprd <- cprd %>%
mutate(yrdrugstart = format(dstartdate, format = "%Y")) %>%
mutate(yrdrugstart = as.numeric(yrdrugstart))
cprd <- cprd %>%
mutate(dstartdate_cutoff = ifelse(dstartdate < "2013-01-01", 1 , NA_real_))
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop patients initiating before 1/1/2013")
print("################################################")
print(table(cprd$dstartdate_cutoff))
print(table(cprd$dstartdate_cutoff, cprd$drugclass))
}
cprd <- cprd %>%
filter(is.na(dstartdate_cutoff))
##### Drop if treated with insulin when starting new drug
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if treated with insulin when starting new drug")
print("################################################")
print(table(cprd$INS))
print(table(cprd$INS, cprd$drugclass))
}
cprd <- cprd %>%
filter(INS == 0)
##### Drop patients with ESRD
describe(cprd$preegfr)
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop patients with ESRD")
print("################################################")
print(table(cprd$preckdstage))
print(table(cprd$preckdstage, cprd$drugclass))
}
cprd <- cprd %>%
filter(preckdstage != "stage_5" & preckdstage != "stage_4" & preckdstage != "stage_3b")
#describe(cprd$preegfr)
cprd <- cprd %>% mutate(egfrl45 = ifelse(preegfr<45,1,NA))
#describe(cprd$egfrl45)
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop patients with EGFR<45")
print("################################################")
print(table(cprd$egfrl45))
print(table(cprd$egfrl45, cprd$drugclass))
}
cprd <- cprd %>%
filter(is.na(egfrl45))
#describe(cprd$preegfr)
##### Drop if first-line treatment
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if first-line treatment")
print("################################################")
print(table(cprd$drugline_all))
print(table(cprd$drugline_all, cprd$drugclass))
}
cprd <- cprd %>%
filter(drugline_all != 1)
##### Drop if semaglutide
# cprd <- cprd %>%
# mutate(semaglutide_drug = ifelse(str_detect(drugsubstances, "Semaglutide"), 1, NA_real_))
#
# # printing inclusion patients
# if (dataset.type == "diagnostics") {
#
# print("################################################")
# print("##### Drop if semaglutide")
# print("################################################")
# print(table(cprd$semaglutide_drug))
#
# }
#
# cprd <- cprd %>%
# filter(is.na(semaglutide_drug))
############################# Variable Prep
### Add variable that identifies an individual entry in the data
cprd <- cprd %>%
mutate(pated = paste(patid, drugclass, dstartdate, sep = ".")) #%>%
##### Drug of interest
##### - DPP4 and SGLT2: drugclass
#mutate(drugclass = factor(drugclass))
# 1 - DPP4; 2 - SGLT2
##### Outcome HbA1c # name: posthba1c12m (missing - 46383)
##### - posthba1c6m but if missing
##### - posthba1c12m
cprd <- cprd %>%
mutate(posthba1cfinal = ifelse(is.na(posthba1c6m), posthba1c12m, posthba1c6m)) %>%
mutate(posthba1cfinal = as.numeric(posthba1cfinal))
##### Outcome Weight # name:
##### - postweight6m but if missing
##### - postweight12m
cprd <- cprd %>%
mutate(postweightfinal = ifelse(is.na(postweight6m), postweight12m, postweight6m)) %>%
mutate(postweightfinal = as.numeric(postweightfinal))
##### Sociodemographic variables
cprd <- cprd %>%
##### - Age: agetx (new var)
mutate(agetx = as.numeric(dstartdate_age)) %>%
##### - Sex: sex
mutate(sex = factor(ifelse(gender == 1, "Male", "Female"))) %>%
##### - Duration of diabetes: t2dmduration
mutate(t2dmduration = as.numeric(dstartdate_dm_dur_all)) %>%
##### - Ethnicity: ethnicity
mutate(ethnicity_5cat = ifelse(is.na(ethnicity_5cat),99,ethnicity_5cat)) %>%
mutate(ethnicity = factor(ethnicity_5cat, levels = c(0, 1, 2, 3, 4, 99), labels = c("White", "South Asian", "Black", "Other", "Mixed", "Missing"))) %>%
mutate(ethnicity_16cat = ifelse(is.na(ethnicity_16cat),99,ethnicity_16cat)) %>%
mutate(ethnicity16 = factor(ethnicity_16cat, levels = c(1:16, 99),
labels = c("British","Irish","Other White","White & Black Caribbean",
"White & Black African", "White & Asian", "Other Mixed", "Indian", "Pakastani",
"Bangladeshi","Other Asian","Caribbean","African","Other Black","Chinese",
"Other Ethnic Group","Missing"))) %>%
##### - Deprivation: deprivation
mutate(deprivation = factor(imd2015_10)) %>%
##### - Smoking Status: smoke
mutate(smoke = factor(smoking_cat)) %>%
##### - Line Therapy: drugline: turn all > 4 to 5+
mutate(drugline = ifelse(drugline_all > 4, 5, drugline_all)) %>%
mutate(drugline.t = as.factor(as.numeric(drugline))) %>%
# mutate(drugline = factor(drugline, levels = c(2, 3, 4, 5), labels = c("2", "3", "4", "5+"))) %>%
##### - Hospitalisations in previous year
mutate(prehospitalisation = factor(hosp_admission_prev_year, levels = c(0, 1), labels = c("No", "Yes")))
##### Diabetes treatment
cprd <- cprd %>%
##### - Drugs taken alongside treatment
# ##### - SU
# ##### - MFN
# ##### - DPP4
# ##### - TZD
# mutate(SU = factor(SU, levels = c(0, 1), labels = c("No", "Yes")),
# MFN = factor(MFN, levels = c(0, 1), labels = c("No", "Yes")),
# DPP4 = factor(DPP4, levels = c(0, 1), labels = c("No", "Yes")),
# TZD = factor(TZD, levels = c(0, 1), labels = c("No", "Yes"))) %>%
mutate(ncurrtx = DPP4 + SGLT2 + GLP1 + TZD + SU + MFN + Acarbose + Glinide - 1) %>%
mutate(ncurrtx = ifelse(ncurrtx > 3, 3, ncurrtx)) %>%
mutate(ncurrtx = factor(ncurrtx, levels = c(0, 1, 2, 3), labels = c("0", "1", "2", "3"))) %>%
##### - Outcome month: hba1cmonth
mutate(hba1cmonth_12 = difftime(posthba1c12mdate, dstartdate, units = "days") / 30) %>%
mutate(hba1cmonth_6 = difftime(posthba1c6mdate, dstartdate, units = "days") / 30) %>%
mutate(hba1cmonth = ifelse(is.na(hba1cmonth_6), hba1cmonth_12, hba1cmonth_6)) %>%
mutate(hba1cmonth = as.numeric(hba1cmonth))
##### Biomarkers
##### - hba1c: prehba1c (Nothing to do)
##### - BMI: prebmi (Nothing to do)
##### - eGFR: preegfr (Nothing to do)
##### - Albumin:Creatine ratio: preacr (Nothing to do)
##### - Serum albumin: prealbumin_blood (remove the _ from the name)
cprd <- cprd %>%
dplyr::rename("prealbuminblood" = "prealbumin_blood",
"prealbuminblooddate" = "prealbumin_blooddate",
"prealbuminblooddrugdiff" = "prealbumin_blooddrugdiff")
##### - Alanine aminotransferase: prealt (Nothing to do)
##### - Aspartate aminotransferase: preast (Nothing to do)
##### - Bilirubin: prebilirubin (Nothing to do)
##### - Fasting glucose: prefastingglucose (Nothing to do)
##### - Fasting haematocrit: prehaematocrit (Nothing to do)
##### - Fasting haemoglobin: prehaemoglobin (Nothing to do)
##### - High-density lipoprotein (HDL): prehdl (Nothing to do)
##### - Mean arterial BP: premap
cprd <- cprd %>%
mutate(premap = predbp + ((presbp - predbp) / 3))
##### - Total cholesterol: pretotalcholesterol (Nothing to do)
##### - Triglycerides: pretriglyceride (Nothing to do)
##### Comorbidities
cprd <- cprd %>%
##### - Angina: predrug_earliest_angina
mutate(preangina = factor(predrug_angina, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Chronic Liver Disease: predrug_earliest_cld
mutate(precld = factor(predrug_cld, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Diabetic Nephropathy: predrug_earliest_diabeticnephropathy
mutate(prediabeticnephropathy = factor(predrug_diabeticnephropathy, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Heart failure: predrug_earliest_heartfailure
mutate(preheartfailure = factor(predrug_heartfailure, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Hypertension: predrug_earliest_hypertension
mutate(prehypertension = factor(predrug_hypertension, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Ischaemic Heart Disease: predrug_earliest_ihd
mutate(preihd = factor(predrug_ihd, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Myocardial Infarction: predrug_earliest_myocardialinfarction
mutate(premyocardialinfarction = factor(predrug_myocardialinfarction, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Neuropathy: predrug_earliest_neuropathy
mutate(preneuropathy = factor(predrug_neuropathy, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Peripheral Arterial Disease: predrug_earliest_pad
mutate(prepad = factor(predrug_pad, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Retinopathy: predrug_earliest_retinopathy
mutate(preretinopathy = factor(predrug_retinopathy, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Cardiac Revascularisation: predrug_earliest_revasc
mutate(prerevasc = factor(predrug_revasc, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Stroke: predrug_earliest_stroke
mutate(prestroke = factor(predrug_stroke, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Transient Ischaemic Attack: predrug_earliest_tia
mutate(pretia = factor(predrug_tia, levels = c(0, 1), labels = c("No", "Yes"))) %>%
##### - Atrial fibrillation: predrug_earliest_af
mutate(preaf = factor(predrug_af, levels = c(0, 1), labels = c("No", "Yes")))
#################### Final dataset - all patients
#
# Add all variables necessary for ALL analysis in the paper.
#
final.dataset <- cprd %>%
select(
# information regarding patient
patid, pated, multi_drug_start, timeprevcombo, drugsubstances,gp_record_end,death_date,
# response hba1c
posthba1cfinal,
# therapies of interest
drugclass,
# Sociodemographic features
agetx, sex, t2dmduration, ethnicity, ethnicity16, deprivation, smoke, prehospitalisation,
# Diabetes treatment
drugline, ncurrtx, hba1cmonth, dstartdate, dstopdate, yrdrugstart, dcstopdate,
# Biomarkers
prehba1c, prebmi, preegfr, preacr, prealbuminblood, prealt, preast, prebilirubin, prefastingglucose,
prehaematocrit, prehaemoglobin, prehdl, premap, pretotalcholesterol, pretriglyceride,
# Comorbidities
preangina, precld, prediabeticnephropathy, preheartfailure, prehypertension, preihd, premyocardialinfarction,
preneuropathy, prepad, preretinopathy, prerevasc, prestroke, pretia, preaf,qrisk2_10yr_score,
# Weight analysis
preweight, postweight12m, postweight6m, postweight12mdate, postweight6mdate, postweightfinal,
# Discontinuation
stopdrug_6m_3mFU,
# eGFR analysis
postegfr12m, postegfr6m,
# mv complications and HF outcome
postdrug_first_diabeticnephropathy, postdrug_first_neuropathy, postdrug_first_retinopathy, postdrug_first_heartfailure, hf_death_any_cause
) %>%
as.data.frame()
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Final dataset - all patients")
print("################################################")
print(nrow(final.dataset))
print(table(final.dataset$drugclass))
}
# if full cohort was requested
if (dataset.type == "full.cohort") {
return(final.dataset)
}
############################### HbA1c model
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### HbA1c model")
print("################################################")
}
##### Drop duplicates (i.e. started treatment on same day)
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop duplicates (i.e. started treatment on same day)")
print("################################################")
print(table(final.dataset$multi_drug_start))
print(table(final.dataset$multi_drug_start, final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(multi_drug_start == 0)
##### Drop if less than 61 days since started previous line of therapy (see Bev finalmerge)
final.dataset <- final.dataset %>%
mutate(timeprevcombo_less61 = ifelse(timeprevcombo <= 61, 1, NA_real_))
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if less than 61 days since started previous line of therapy (see Bev finalmerge)")
print("################################################")
print(table(final.dataset$timeprevcombo_less61))
print(table(final.dataset$timeprevcombo_less61, final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(is.na(timeprevcombo_less61))
##### Drop if HbA1c <53
final.dataset <- final.dataset %>%
mutate(hb_extreme_53 = ifelse(prehba1c < 53, 1, NA_real_))
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if HbA1c <53")
print("################################################")
print(table(final.dataset$hb_extreme_53))
print(table(final.dataset$hb_extreme_53, final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(is.na(hb_extreme_53))
##### Drop if HbA1c >120
final.dataset <- final.dataset %>%
mutate(hb_extreme_120 = ifelse(prehba1c >120, 1, NA_real_))
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if HbA1c <120")
print("################################################")
print(table(final.dataset$hb_extreme_120))
print(table(final.dataset$hb_extreme_53, final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(is.na(hb_extreme_120))
##### Drop if HbA1c is missing
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if HbA1c is missing")
print("################################################")
print(table(is.na(final.dataset$prehba1c)))
print(table(is.na(final.dataset$prehba1c), final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(!is.na(prehba1c))
##### Drop if post HbA1c missing
# # printing inclusion patients
# if (dataset.type == "diagnostics") {
#
# print("################################################")
# print("##### Drop if post HbA1c missing")
# print("################################################")
# print(table(is.na(final.dataset$posthba1cfinal)))
# print(table(is.na(final.dataset$posthba1cfinal), final.dataset$drugclass))
#
# }
#
# # final.dataset <- final.dataset %>%
# # filter(!is.na(posthba1cfinal))
##### Drop if ethnicity missing
# printing inclusion patients
if (dataset.type == "diagnostics") {
print("################################################")
print("##### Drop if ethnicity missing")
print("################################################")
print(table(final.dataset$ethnicity=="Missing"))
print(table(final.dataset$ethnicity=="Missing", final.dataset$drugclass))
}
final.dataset <- final.dataset %>%
filter(ethnicity!="Missing") %>%
mutate(ethnicity=factor(ethnicity))
print(table(final.dataset$ethnicity))
print(table(final.dataset$ethnicity, final.dataset$drugclass))
print(table(final.dataset$ethnicity16, final.dataset$drugclass))
##### IMPORT ALL SGLT2, DPP4, GLP1 + TZD STARTS FOR LATER CENSORING (SGLT2 for DPP4SU arm only)
### Combine with main dataset to get next SGLT2/GLP1/TZD/DPP4 start date
### Also get latest SGLT2 stop date before drug start for DPP4 arm in case needed for sensitivity analysis
load(paste0(data_dir,"20221212_t2d_all_drug_periods.Rda"))
later_sglt2 <- final.dataset %>%
select(patid, dstartdate) %>%
inner_join((t2d_all_drug_periods %>%
filter(drugclass=="SGLT2") %>%
select(patid, next_sglt2=dstartdate)), by="patid") %>%
filter(next_sglt2>dstartdate) %>%
group_by(patid, dstartdate) %>%
summarise(next_sglt2_start=min(next_sglt2, na.rm=TRUE)) %>%
ungroup()
later_dpp4 <- final.dataset%>%
select(patid, dstartdate) %>%
inner_join((t2d_all_drug_periods %>%
filter(drugclass=="DPP4") %>%
select(patid, next_dpp4=dstartdate)), by="patid") %>%
filter(next_dpp4>dstartdate) %>%
group_by(patid, dstartdate) %>%
summarise(next_dpp4_start=min(next_dpp4, na.rm=TRUE)) %>%
ungroup()
later_glp1 <- final.dataset%>%
select(patid, dstartdate) %>%
inner_join((t2d_all_drug_periods %>%
filter(drugclass=="GLP1") %>%
select(patid, next_glp1=dstartdate)), by="patid") %>%
filter(next_glp1>dstartdate) %>%
group_by(patid, dstartdate) %>%
summarise(next_glp1_start=min(next_glp1, na.rm=TRUE)) %>%
ungroup()
later_tzd <- final.dataset %>%
select(patid, dstartdate) %>%
inner_join((t2d_all_drug_periods %>%
filter(drugclass=="TZD") %>%
select(patid, next_tzd=dstartdate)), by="patid") %>%
filter(next_tzd>dstartdate) %>%
group_by(patid, dstartdate) %>%
summarise(next_tzd_start=min(next_tzd, na.rm=TRUE)) %>%
ungroup()
last_sglt2_stop <- final.dataset %>%
select(patid, dstartdate) %>%
inner_join((t2d_all_drug_periods %>%
filter(drugclass=="SGLT2") %>%
select(patid, last_sglt2=dstopdate)), by="patid") %>%
filter(last_sglt2<dstartdate) %>%
group_by(patid, dstartdate) %>%
summarise(last_sglt2_stop=min(last_sglt2, na.rm=TRUE)) %>%
ungroup()
final.dataset <- final.dataset %>%
left_join(later_sglt2, by=c("patid", "dstartdate")) %>%
left_join(later_dpp4, by=c("patid", "dstartdate")) %>%
left_join(later_glp1, by=c("patid", "dstartdate")) %>%
left_join(later_tzd, by=c("patid", "dstartdate")) %>%
left_join(last_sglt2_stop, by=c("patid", "dstartdate"))
#### Microvascular complications
#Pre-existing composite, and survival analysis setup
final.dataset <- final.dataset %>%
mutate(predrug.mv = ifelse(prediabeticnephropathy=="Yes" | preneuropathy=="Yes" | preretinopathy=="Yes", 1, 0),
postdrug.mv=pmin(postdrug_first_diabeticnephropathy, postdrug_first_neuropathy, postdrug_first_retinopathy, na.rm=TRUE))
#Check
table(final.dataset$prediabeticnephropathy)
table(final.dataset$preneuropathy)
table(final.dataset$preretinopathy)
table(final.dataset$predrug.mv)
describe(final.dataset$postdrug_first_diabeticnephropathy)
describe(final.dataset$postdrug_first_neuropathy)
describe(final.dataset$postdrug_first_retinopathy)
describe(final.dataset$postdrug.mv)
#ITT MV complications
# Find censoring dates - earliest of:
## 5 years from dstartdate
## Death
## Start SGLT2 (DPP4 arm), or DPP4 (SGLT2 arm)
## End of GP records
## MV complications
final.dataset <- final.dataset %>%
mutate(five_years_post_dstart=dstartdate+(365.25*5),
mv_itt_censdate=if_else(drugclass=="SGLT2",
pmin(five_years_post_dstart,
death_date,
next_dpp4_start,
gp_record_end,
postdrug.mv, na.rm=TRUE),
if_else(drugclass=="DPP4",
pmin(five_years_post_dstart,
death_date,
next_sglt2_start,
gp_record_end,
postdrug.mv, na.rm=TRUE),
as.Date(NA))),
mv_itt_censvar=ifelse((!is.na(postdrug.mv) & mv_itt_censdate==postdrug.mv), 1, 0),
mv_itt_censtime_yrs=as.numeric(difftime(mv_itt_censdate, dstartdate, unit="days"))/365.25)
# describe(final.dataset$mv_itt_censdate)
# describe(final.dataset$mv_itt_censvar)
# describe(final.dataset$mv_itt_censtime_yrs)
#PP MV complications
# Find censoring dates - earliest of:
## 5 years from dstartdate
## Death
## Any change in glucose-lowering therapy
## End of GP records
## MV complications
final.dataset <- final.dataset %>%
mutate(mv_pp_censdate=if_else(drugclass=="SGLT2",
pmin(five_years_post_dstart,
death_date,
gp_record_end,
postdrug.mv,
dcstopdate, na.rm=TRUE),
if_else(drugclass=="DPP4",
pmin(five_years_post_dstart,
death_date,
gp_record_end,
postdrug.mv,
dcstopdate, na.rm=TRUE), as.Date(NA))),
mv_pp_censvar=ifelse(!is.na(postdrug.mv) & mv_pp_censdate==postdrug.mv, 1, 0),
mv_pp_censtime_yrs=as.numeric(difftime(mv_pp_censdate, dstartdate, unit="days"))/365.25)
# describe(final.dataset$mv_pp_censdate)
# describe(final.dataset$mv_pp_censvar)
# describe(final.dataset$mv_pp_censtime_yrs)
#### Retinopathy, and survival analysis setup
final.dataset <- final.dataset %>%
mutate(predrug.ret = ifelse(preretinopathy=="Yes", 1, 0),
postdrug.ret=pmin(postdrug_first_retinopathy, na.rm=TRUE))
#Check
table(final.dataset$preretinopathy)
table(final.dataset$predrug.ret)
describe(final.dataset$postdrug_first_retinopathy)
describe(final.dataset$postdrug.ret)
#ITT Retinopathy
# Find censoring dates - earliest of:
## 5 years from dstartdate
## Death
## Start SGLT2 (DPP4 arm), or DPP4 (SGLT2 arm)
## End of GP records
## Retinopathy
final.dataset <- final.dataset %>%
mutate(five_years_post_dstart=dstartdate+(365.25*5),
ret_itt_censdate=if_else(drugclass=="SGLT2",
pmin(five_years_post_dstart,
death_date,
next_dpp4_start,
gp_record_end,
postdrug.ret, na.rm=TRUE),
if_else(drugclass=="DPP4",
pmin(five_years_post_dstart,
death_date,
next_sglt2_start,
gp_record_end,
postdrug.ret, na.rm=TRUE),
as.Date(NA))),
ret_itt_censvar=ifelse((!is.na(postdrug.ret) & mv_itt_censdate==postdrug.ret), 1, 0),
ret_itt_censtime_yrs=as.numeric(difftime(mv_itt_censdate, dstartdate, unit="days"))/365.25)
#PP retinopathy
# Find censoring dates - earliest of:
## 5 years from dstartdate
## Death
## Any change in glucose-lowering therapy
## End of GP records
## Retinopathy
final.dataset <- final.dataset %>%
mutate(ret_pp_censdate=if_else(drugclass=="SGLT2",
pmin(five_years_post_dstart,
death_date,
gp_record_end,
postdrug.ret,
dcstopdate, na.rm=TRUE),
if_else(drugclass=="DPP4",
pmin(five_years_post_dstart,
death_date,
gp_record_end,
postdrug.ret,
dcstopdate, na.rm=TRUE), as.Date(NA))),
ret_pp_censvar=ifelse(!is.na(postdrug.mv) & mv_pp_censdate==postdrug.mv, 1, 0),
ret_pp_censtime_yrs=as.numeric(difftime(mv_pp_censdate, dstartdate, unit="days"))/365.25)
#Save
save(final.dataset,file=paste0(data_dir,"final.dataset.sglt2.dpp4.val.Rda"))
#### Load data ####
#Dataset define in prep
load(paste0(data_dir,"final.dataset.sglt2.dpp4.val.Rda"))
#GOLD SGLT2-DPP4 model
load("C:/Users/jmd237/OneDrive - University of Exeter/John/Projects/2019_SGLT2vsDPP4/results/m1_hba1cmodel.Rdata")
#GOLD SGLT2-DPP4 model for discontinuation
load("C:/Users/jmd237/OneDrive - University of Exeter/John/Projects/2019_SGLT2vsDPP4/results/m1_discontinuationmodel.Rdata")
#GOLD SGLT2-DPP4 model for weight
load("C:/Users/jmd237/OneDrive - University of Exeter/John/Projects/2019_SGLT2vsDPP4/results/m1_weightmodel.Rdata")
#### Useful functions and global settings ####
#Global settings
#model.name <- "unadj"
#OR
model.name <- "full"
#OR
#model.name <- "simple"
pdfwidth <- 14
pdfheight <- 10
pngwidth <- 3200
pngheight <- 2400
pngres <- 200
row_names <- matrix(c("Predicted SGLT2i glycaemic benefit",paste0(intToUtf8(8805),"5 mmol/mol"), "3-5 mmol/mol","0-3 mmol/mol",
"Predicted DPP4i glycaemic benefit","0-3 mmol/mol", paste0(intToUtf8(8805),"3 mmol/mol")))
tick.hb <- c(-10,-7.5,-5,-2.5,0,2.5,5,7.5, 10)
tick.hb.resp <- c(-18,-15,-12,-9,-6,-3,0,3)
tick.dc <- c(0,5,10,15,20,25,30,35,40)
tick.wt <- c(-4,-3,-2,-1,0)
B <- 1000
#Add dummy legend
dummy <- final.dataset %>%
sample_n(1000) %>%
mutate(drugclass = ifelse(drugclass=="SGLT2","SGLT2 inhibitor","DPP-4 inhibitor")) %>%
ggplot(aes(x = prehba1c, y = prebmi, group=drugclass)) +
scale_color_manual(values=c("#4118de","#f1a340")) +
geom_point(aes(colour=drugclass), size = 1.5) + theme_bw() +
theme(legend.text = element_text(colour="black", size=rel(1))) +
theme(legend.title=element_blank()) +
theme(legend.direction = "horizontal",
legend.position = "bottom",
legend.box = "horizontal"
) +
guides(colour = guide_legend(override.aes = list(size=4)))
# Create user-defined function, which extracts legends from ggplots #https://statisticsglobe.com/add-common-legend-to-combined-ggplot2-plots-in-r/
extract_legend <- function(my_ggp) {
step1 <- ggplot_gtable(ggplot_build(my_ggp))
step2 <- which(sapply(step1$grobs, function(x) x$name) == "guide-box")
step3 <- step1$grobs[[step2]]
return(step3)
}
# Apply user-defined function to extract legend
shared_legend <- extract_legend(dummy)
#Define HTE treatment diff plot function
hist_plot <- function(data,sx,sy,y) {
#label for hist
annotation <- data.frame(
x = c(sx,sy),
y = c(y),
label = c("Favours SGLT2i", "Favours DPP4i")
)
#define data
dat <- data %>% dplyr::select(hba1c_diff) %>% mutate(above=ifelse(hba1c_diff> 0, "Favours DPP4i", "Favours SGLT2i"))
c_low <- quantile(dat$hba1c_diff,.001)
c_upp <- quantile(dat$hba1c_diff,.999)
c_lowr <- 2*round(c_low/2)
c_uppr <- 2*round(c_upp/2)
c_low <- min(dat$hba1c_diff,.001)
c_upp <- quantile(dat$hba1c_diff,.999)
c_lowr <- 2*round(c_low/2)
c_uppr <- 2*round(c_upp/2)
#plot
ggplot(data=dat, aes(x=hba1c_diff,fill=above)) +
geom_histogram(position="identity", alpha=0.5,color="black",breaks=seq(-15,10,by=1)) +
geom_vline(aes(xintercept=0), linetype="dashed")+
labs(title="",x="HbA1c difference (mmol/mol)", y = "Number of people") +
#scale_x_continuous(limits=c(c_low,c_upp),breaks=c(seq(c_lowr,c_uppr,by=2))) +
scale_fill_manual(values=c("#998ec3","#f1a340"))+
theme_classic() + theme(legend.position = "none")
#theme(legend.position = c(0.87, 0.97)) + theme(legend.title = element_blank())
#geom_text(data=annotation, aes(x=x, y=y, label=label),color=c("#f1a340","#998ec3"),size=4, fontface="bold" )
}
#Function to fit a series of models and output the coefficient(s) of interest with CIs and p-value
hte.model.coefs <- function(x,nmodels) {
mnumber = c(1:nmodels)
models <- as.list(1:nmodels)
nobs <- vector()
coef <- vector()
lower <- vector()
upper <- vector()
pvalue <- vector()
data <- x
for(i in mnumber) {
models[[i]] <- lm(as.formula(f[[i]]),data=data)
nobs <- append(nobs,nobs(models[[i]]))
coef <- append(coef,models[[i]]$coefficients[2])
confint_all <- confint(models[[i]], levels=0.95)
lower <- append(lower,confint_all[2,1])
upper <- append(upper,confint_all[2,2])
pvalue <- append(pvalue,summary(models[[i]])$coefficients[2,4])
}
datasetname = c(deparse(substitute(x)),deparse(substitute(x)),deparse(substitute(x)))
x <- data.frame(datasetname,modelname,cbind(nobs,coef,lower,upper,pvalue))
rownames(x) <- c()
return(x)
}
#Function to output HTE by subgroup
hte_plot <- function(data,pred,obs,obslowerci,obsupperci,ymin.ymax) {
#ymin <- min(data$lci); ymax <- max(data$uci);yminr <- 2*round(ymin/2); ymaxr <- 2*round(ymax/2)
ymin <- -14; ymax <- 14
ggplot(data=data,aes_string(x=pred,y=obs)) +
geom_vline(xintercept=0, linetype="dashed", color = "grey60") + geom_hline(yintercept=0, linetype="dashed", color = "grey60") +
geom_abline(intercept=0,slope=1, color="red", lwd=0.75) + ggtitle("") +
geom_point(alpha=1) + theme_classic() +
geom_errorbar(aes_string(ymin=obslowerci, ymax=obsupperci), colour="black", width=.1) +
ylab("Observed HbA1c difference (mmol/mol)*") + xlab("Predicted HbA1c difference (mmol/mol)") +
scale_x_continuous(limits=c(ymin,ymax),breaks=c(seq(ymin,ymax,by=2))) +
scale_y_continuous(limits=c(ymin,ymax),oob=rescale_none,breaks=c(seq(ymin,ymax,by=2))) +
# scale_x_continuous(limits=c(ymin,ymax),breaks=c(seq(yminr,ymaxr,by=2))) +
# scale_y_continuous(limits=c(ymin,ymax),breaks=c(seq(yminr,ymaxr,by=2))) +
theme_base(base_size = 8) +
theme(plot.background = element_blank()) + theme(axis.text.x=element_text(size=8),axis.text.y=element_text(size=8)) +
theme(text = element_text(size = 10),
# axis.ticks.x = element_blank(),
# axis.ticks.y = element_blank(),
axis.ticks.x = element_line(colour = "grey50"),
axis.ticks.y = element_line(colour = "grey50"),
axis.line = element_line(colour = "grey50" ),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
}
#Model and extract HTE coefficients for subgroups
hte_model <- function(data) {
final <- data
#Define subsets of interest to calc HTE
#overall
overall <- final
#sglt2.best
sglt2.best <- final %>% dplyr::filter(bestdrug=="SGLT2")
#dpp4.best
dpp4.best <- final %>% dplyr::filter(bestdrug=="DPP4")
#match trials
#df1 <- final %>% dplyr::filter(hba1c_diff<= -10)
df2 <- final %>% dplyr::filter(hba1c_diff<= -5)
df3 <- final %>% dplyr::filter(hba1c_diff<= -3 & hba1c_diff > -5)
df4 <- final %>% dplyr::filter(hba1c_diff> -3 & hba1c_diff <= 0)
df5 <- final %>% dplyr::filter(hba1c_diff> 0 & hba1c_diff < 3)
df6 <- final %>% dplyr::filter(hba1c_diff>= 3)
#df7 <- final %>% dplyr::filter(hba1c_diff>= 5)
#Run HTE models and extract coefs for each subset
dflist <- list(overall,sglt2.best,dpp4.best,df2,df3,df4,df5,df6)
res.list <- lapply(dflist, function(df) {
hte.model.coefs(df,3)
})
res.list <- bind_rows(res.list, .id="column_label")
res.lab <- c(rep("overall",3),rep("sglt2.best",3),rep("dpp4.best",3),rep("sglt.best5",3),rep("sglt.best3",3),rep("sglt.best0-3",3),
rep("dpp4.best0-3",3),rep("dpp4.best3",3))
res.list <- data.frame(res.lab,res.list) %>% dplyr::select(-column_label,-datasetname)
res.list %>% dplyr::filter(modelname==model.name) #final adjusted list
#Calibration plot HTE
#Unadjusted obs vs pred
#Define tenths
final <- final %>% mutate(hba1c_diff.q = ntile(hba1c_diff, 10))
#define dataset with predicted values
t1 <- final %>%
group_by(hba1c_diff.q) %>%
dplyr::summarise(N = length(hba1c_diff),
hba1c_diff.pred = mean(hba1c_diff))
#check some patients actually prescribed both drugs in each tenth
# ddply(final, c("hba1c_diff.q","drugclass"), dplyr::summarise,
# N = length(posthba1c_final),
# posthba1c_final.m = mean(posthba1c_final),
# se = sd(posthba1c_final)/sqrt((length(posthba1c_final))))
#obs vs pred, by decile of predicted treatment difference
#For Formula 1-3
mnumber = c(1:10)
models <- as.list(1:10)
hba1c_diff.obs.unadj <- vector()
lower.unadj <- vector()
upper.unadj <- vector()
hba1c_diff.obs.sim <- vector()
lower.sim <- vector()
upper.sim <- vector()
hba1c_diff.obs.adj <- vector()
lower.adj <- vector()
upper.adj <- vector()
#Unadj
for(i in mnumber) {
models[[i]] <- lm(as.formula(formula1),data=final,subset=hba1c_diff.q==i)
hba1c_diff.obs.unadj <- append(hba1c_diff.obs.unadj,models[[i]]$coefficients[2])
confint_all <- confint(models[[i]], levels=0.95)
lower.unadj <- append(lower.unadj,confint_all[2,1])
upper.unadj <- append(upper.unadj,confint_all[2,2])
}
#Simple
for(i in mnumber) {
models[[i]] <- lm(as.formula(formula2),data=final,subset=hba1c_diff.q==i)
hba1c_diff.obs.sim <- append(hba1c_diff.obs.sim,models[[i]]$coefficients[2])
confint_all <- confint(models[[i]], levels=0.95)
lower.sim <- append(lower.sim,confint_all[2,1])
upper.sim <- append(upper.sim,confint_all[2,2])
}
#Full
for(i in mnumber) {
models[[i]] <- lm(as.formula(formula3),data=final,subset=hba1c_diff.q==i)
hba1c_diff.obs.adj <- append(hba1c_diff.obs.adj,models[[i]]$coefficients[2])
confint_all <- confint(models[[i]], levels=0.95)
lower.adj <- append(lower.adj,confint_all[2,1])
upper.adj <- append(upper.adj,confint_all[2,2])
}
#Final data.frame
t1 <- data.frame(t1,cbind(hba1c_diff.obs.unadj,lower.unadj,upper.unadj,
hba1c_diff.obs.sim,lower.sim,upper.sim,
hba1c_diff.obs.adj,lower.adj,upper.adj))
#unadj
# plotdata <- t1 %>% dplyr::mutate(obs=hba1c_diff.obs.unadj,lci=lower.unadj,uci=upper.unadj)
# hte_plot(plotdata,"hba1c_diff.pred","obs","lci","uci")
# #simple adj
# plotdata <- t1 %>% dplyr::mutate(obs=hba1c_diff.obs.sim,lci=lower.sim,uci=upper.sim)
# hte_plot(plotdata,"hba1c_diff.pred","obs","lci","uci")
#splie adj
plotdata <- t1 %>% dplyr::mutate(obs=hba1c_diff.obs.adj,lci=lower.adj,uci=upper.adj)
hte_plot(plotdata,"hba1c_diff.pred","obs","lci","uci")
#outputs
hist <- hist_plot(final,-2.5,2.3,1100)
hte <- hte_plot(plotdata,"hba1c_diff.pred","obs","lci","uci")
res.list <- res.list %>% filter(modelname==model.name & res.lab != "sglt.best10" & res.lab != "dpp4.best5" & res.lab != "overall") %>%
mutate(order=c(1,5,2,3,4,6,7)) %>%
arrange(order)
return(list(hist,hte,res.list))
}
#Forest plot for calibration comparison within ethnicity
fp_plot <- function(coef,cim,cip) {
fp <-
forestplot(row_names,
mean = coef,
lower= cim,
upper = cip,
hrzl_lines = gpar(col="#444444"),#lineheight=unit(2,'cm'),
is.summary = c(TRUE,rep(FALSE,3),TRUE,rep(FALSE,2)),
#title="c) TZD - Oedema",
xticks = tick.hb,
zero = 0,