-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathPrediction_CSC.Rmd
1786 lines (1558 loc) · 46.4 KB
/
Prediction_CSC.Rmd
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: "External validation of the performance of competing risks prediction models: a guide through modern methods - Cause specific hazard models"
always_allow_html: true
output:
github_document:
toc: true
toc_depth: 5
keep_text: true
pandoc_args: --webtex
---
## Steps
The steps taken in this file are:
1. To develop a competing risks prediction model using the cause specific hazards approach.
2. To assess the performance of the model in terms of calibration, discrimination and overall prediction error. We calculate the apparent (no internal validation) validation and the external validation.
3. To assess the potential clinical utility the model using decision curve analysis.
### Installing and loading packages and import data
The following libraries are used in this file, the code chunk below will a) check whether you already have them installed, b) install them for you if not already present, and c) load the packages into the session.
```{r setup, include=FALSE}
# Knitr options
knitr::opts_chunk$set(
fig.retina = 3,
fig.path = "imgs/Prediction_CSC/",
echo = FALSE
)
```
```{r, wdlib, message=FALSE, warning=FALSE, echo=TRUE}
# Use pacman to check whether packages are installed, if not load
if (!require("pacman")) install.packages("pacman")
library(pacman)
pacman::p_load(
survival,
rms,
cmprsk,
riskRegression,
mstate,
pseudo,
pec,
riskRegression,
plotrix,
knitr,
splines,
kableExtra,
gtsummary,
boot,
tidyverse,
rsample,
gridExtra,
webshot
)
# Import data ------------------
rdata <- readRDS(here::here("Data/rdata.rds"))
vdata <- readRDS(here::here("Data/vdata.rds"))
rdata$hr_status <- relevel(rdata$hr_status, ref = "ER and/or PR +")
vdata$hr_status <- relevel(vdata$hr_status, ref = "ER and/or PR +")
```
We loaded the development data (rdata) and the validation data (vdata).
More details about development and validation data are provided in the manuscript.
### Descriptive statistics
```{r, import}
rsel <- rdata[, c("id", "age", "size", "ncat", "hr_status")]
vsel <- vdata[, c("id", "age", "size", "ncat", "hr_status")]
rsel$dt <- 1
vsel$dt <- 2
cdata <- rbind(rsel, vsel)
cdata$dt <- factor(
cdata$dt,
levels = c(1, 2),
labels = c("Development data", "Validation data")
)
label(cdata$age) <- "Age"
label(cdata$size) <- "Size"
label(cdata$ncat) <- "Nodal status"
label(cdata$hr_status) <- "Hormon receptor status"
units(cdata$age) <- "years"
units(cdata$size) <- "cm"
```
```{r tab1_bis}
gtsummary::tbl_summary(
data = cdata |> select(-id),
label = list(age ~ "Age (years)", size ~ "Size (cm)"),
by = "dt",
type = all_continuous() ~ "continuous2",
statistic = all_continuous() ~ c(
"{mean} ({sd})",
"{median} ({min}, {max})"
),
) |>
gtsummary::as_kable_extra() |>
kableExtra::kable_styling("striped")
```
## Goal 1 - develop a competing risks prediction model
### 1.1 Cumulative incidence curves
First, we draw the cumulative incidence curves of breast cancer recurrence.
<details>
<summary>Click to expand code</summary>
```{r, cuminc, fig.align='center', eval=FALSE, echo=TRUE}
# Expand datasets -------------------------
# Expand data to prepare for fitting the model
rdata.w <- crprep(
Tstop = "time",
status = "status_num",
trans = c(1, 2),
id = "id",
keep = c("age", "size", "ncat", "hr_status"),
data = rdata
)
# Save extended data with weights for recurrence (failcode=1)
# and non recurrence mortality (failcode=2)
rdata.w1 <- rdata.w |> filter(failcode == 1)
rdata.w2 <- rdata.w |> filter(failcode == 2)
vdata.w <- crprep(
Tstop = "time",
status = "status_num",
trans = c(1, 2),
id = "id",
keep = c("age", "size", "ncat", "hr_status"),
data = vdata
)
vdata.w1 <- vdata.w |> filter(failcode == 1)
vdata.w2 <- vdata.w |> filter(failcode == 2)
# Development set --------
mfit_rdata <- survfit(
Surv(Tstart, Tstop, status == 1) ~ 1,
data = rdata.w1,
weights = weight.cens
)
mfit_vdata <- survfit(
Surv(Tstart, Tstop, status == 1) ~ 1,
data = vdata.w1,
weights = weight.cens
)
par(xaxs = "i", yaxs = "i", las = 1)
oldpar <- par(mfrow = c(1, 2), mar = c(5, 5, 1, 1))
plot(
mfit_rdata,
col = 1, lwd = 2,
xlab = "Years since BC diagnosis",
ylab = "Cumulative incidence recurrence", bty = "n",
ylim = c(0, 0.25),
xlim = c(0, 5),
fun = "event",
conf.int = TRUE
)
title("Development data")
plot(
mfit_vdata,
col = 1, lwd = 2,
xlab = "Years since BC diagnosis",
ylab = "Cumulative incidence recurrence", bty = "n",
ylim = c(0, 0.25),
xlim = c(0, 5),
fun = "event",
conf.int = TRUE
)
title("Validation data")
par(oldpar)
# Cumulative incidences
smfit_rdata <- summary(mfit_rdata, times = c(1, 2, 3, 4, 5))
smfit_vdata <- summary(mfit_vdata, times = c(1, 2, 3, 4, 5))
```
</details>
```{r, cuminc, fig.align='center', eval=TRUE}
```
The R packages and functions `cmprsk::cuminc()` and `mstate::Cuminc()`are good and easy alternatives to estimate the cumulative incidence function.
```{r, res_ci, fig.align='center'}
res_ci <- cbind(
1 - smfit_rdata$surv,
1 - smfit_rdata$upper,
1 - smfit_rdata$lower,
1 - smfit_vdata$surv,
1 - smfit_vdata$upper,
1 - smfit_vdata$lower
)
res_ci <- round(res_ci, 2)
rownames(res_ci) <- c("1-year", "2-year", "3-year", "4-year", "5-year")
colnames(res_ci) <- rep(c("Estimate", "Lower .95", "Upper .95"), 2)
kable(res_ci, row.names = TRUE) |>
kable_styling("striped", position = "center") |>
add_header_above(c(" " = 1, "Development data" = 3, "Validation data" = 3))
```
The 5-year cumulative incidence of breast cancer recurrence was 14% (95% CI: 11-16%), and 10% (95%CI: 8-12%).
### 1.2 Check non-linearity of continuous predictors
Here we investigate the potential non-linear relation between continuous predictors (i.e. age and size) and the outcomes. We apply three-knot restricted cubic splines using `rms::rcs()` function (details are given in e.g. Frank Harrell's book 'Regression Model Strategies (second edition)', page 27. We assess the potential non-linearity graphically (plotting the two continuous predictors against the log relative hazards (XB or linear predictor) of both event types. Also, we compare the models with and without splines based on the AIC using `stats::AIC()`.
<details>
<summary>Click to expand code</summary>
```{r,ff, warning=FALSE, fig.align='center', eval=FALSE, echo=TRUE}
# Models without splines
fit_csh <- CSC(
Hist(time, status_num) ~ age + size + ncat + hr_status,
data = rdata,
fitter = "cph"
)
fit_csc1 <- fit_csh$models$`Cause 1`
fit_csc2 <- fit_csh$models$`Cause 2`
# Models with splines
dd <- datadist(rdata)
options(datadist = "dd")
# Recurrence
fit_csc1_rcs <- cph(
Surv(time, status_num == 1) ~ rcs(age, 3) + rcs(size, 3) + ncat + hr_status,
x = T,
y = T,
surv = T,
data = rdata
)
# print(fit_csc1_rcs)
# print(summary(fit_csc1_rcs))
# print(anova(fit_csc1_rcs))
P_csc1_age_rcs <- Predict(fit_csc1_rcs, "age")
P_csc1_size_rcs <- Predict(fit_csc1_rcs, "size")
options(datadist = NULL)
# Non-recurrence mortality
dd <- datadist(rdata)
options(datadist = "dd")
fit_csc2_rcs <- cph(
Surv(time, status_num == 2) ~ rcs(age, 3) + rcs(size, 3) + ncat + hr_status,
x = T,
y = T,
surv = T,
data = rdata
)
# print(fit_csc2_rcs)
# print(summary(fit_csc2_rcs))
# print(anova(fit_csc2_rcs))
P_csc2_age_rcs <- Predict(fit_csc2_rcs, "age")
P_csc2_size_rcs <- Predict(fit_csc2_rcs, "size")
options(datadist = NULL)
oldpar <- par(mfrow = c(2, 2), mar = c(5, 5, 1, 1))
par(xaxs = "i", yaxs = "i", las = 1)
plot(
P_csc1_age_rcs$age,
P_csc1_age_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Age at breast cancer diagnosis",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(65, 95)
)
polygon(
c(P_csc1_age_rcs$age, rev(P_csc1_age_rcs$age)),
c(P_csc1_age_rcs$lower, rev(P_csc1_age_rcs$upper)),
col = "grey75",
border = FALSE
)
par(new = TRUE)
plot(
P_csc1_age_rcs$age,
P_csc1_age_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Age at breast cancer diagnosis",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(65, 95)
)
title("Recurrence")
# CSC 1- size
par(xaxs = "i", yaxs = "i", las = 1)
plot(
P_csc1_size_rcs$size,
P_csc1_size_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Size of breast cancer",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(0, 7)
)
polygon(
c(P_csc1_size_rcs$size, rev(P_csc1_size_rcs$size)),
c(P_csc1_size_rcs$lower, rev(P_csc1_size_rcs$upper)),
col = "grey75",
border = FALSE
)
par(new = TRUE)
plot(
P_csc1_size_rcs$size,
P_csc1_size_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Size of breast cancer",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(0, 7)
)
title("Recurrence")
par(xaxs = "i", yaxs = "i", las = 1)
options(datadist = NULL)
# CSC 2- age
plot(
P_csc2_age_rcs$age,
P_csc2_age_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Age at breast cancer diagnosis",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(65, 95)
)
polygon(
c(P_csc2_age_rcs$age, rev(P_csc2_age_rcs$age)),
c(P_csc2_age_rcs$lower, rev(P_csc2_age_rcs$upper)),
col = "grey75",
border = FALSE
)
par(new = TRUE)
plot(
P_csc2_age_rcs$age,
P_csc2_age_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Age at breast cancer diagnosis",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(65, 95)
)
title("Non recurrence mortality")
# CSC 2 - size
par(xaxs = "i", yaxs = "i", las = 1)
plot(
P_csc2_size_rcs$size,
P_csc2_size_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Size of breast cancer",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(0, 7)
)
polygon(
c(P_csc2_size_rcs$size, rev(P_csc2_size_rcs$size)),
c(P_csc2_size_rcs$lower, rev(P_csc2_size_rcs$upper)),
col = "grey75",
border = FALSE
)
par(new = TRUE)
plot(
P_csc2_size_rcs$size,
P_csc2_size_rcs$yhat,
type = "l",
lwd = 2,
col = "blue",
bty = "n",
xlab = "Size of breast cancer",
ylab = "log Relative Hazard",
ylim = c(-2, 2),
xlim = c(0, 7)
)
title("Non recurrence mortality")
options(datadist = NULL)
par(oldpar)
```
</details>
```{r,ff, warning=FALSE, fig.align='center', eval=TRUE}
```
```{r, res_aic, fig.align='center'}
res_AIC <- matrix(c(
AIC(fit_csc1), AIC(fit_csc1_rcs),
AIC(fit_csc2), AIC(fit_csc2_rcs)
),
byrow = T,
ncol = 2,
nrow = 2,
dimnames =
list(
c(
"Recurrence specific hazard",
"Non recurrence mortality"
),
c(
"AIC without splines",
"AIC with splines"
)
)
)
kable(res_AIC, row.names = TRUE) |>
kable_styling("striped", position = "center")
```
Both the graphical comparison and the AIC comparison suggested no relevant departure from linear relations between the continuous predictors (age and size) and the cause-specific hazards (recurrence and non-recurrence mortality).
### 1.3 Checking proportional hazards assumption
We now examine the fits further by checking the proportionality of the cause-specific hazards.
<details>
<summary>Click to expand code</summary>
```{r,ph_csc1, message=FALSE, warning=FALSE,fig.align='center', echo=TRUE, eval=FALSE}
zp_csc1 <- cox.zph(fit_csc1, transform = "identity")
par(las = 1, xaxs = "i", yaxs = "i")
# c(bottom, left, top, right)
oldpar <- par(mfrow = c(2, 2), mar = c(5, 6.1, 3.1, 1))
sub_title <- c("Age", "Size", "Lymph node status", "HR status")
for (i in 1:4) {
plot(
zp_csc1[i],
resid = F,
bty = "n",
xlim = c(0, 5)
)
abline(0, 0, lty = 3)
title(sub_title[i])
}
mtext("Recurrence", side = 3, line = -1, outer = TRUE, font = 2)
par(oldpar)
kable(round(zp_csc1$table, 3)) |>
kable_styling("striped", position = "center")
```
</details>
```{r,ph_csc1, message=FALSE, warning=FALSE,fig.align='center', echo=FALSE, eval=TRUE}
```
<details>
<summary>Click to expand code</summary>
```{r,ph_csc2, message=FALSE, warning=FALSE,fig.align='center',echo=TRUE,eval=FALSE}
zp_csc2 <- cox.zph(fit_csc2, transform = "identity")
par(las = 1, xaxs = "i", yaxs = "i")
# c(bottom, left, top, right)
oldpar <- par(mfrow = c(2, 2), mar = c(5, 6.1, 3.1, 1))
sub_title <- c("Age", "Size", "Lymph node status", "HR status")
for (i in 1:4) {
plot(
zp_csc2[i],
resid = F,
bty = "n",
xlim = c(0, 5)
)
abline(0, 0, lty = 3)
title(sub_title[i])
}
mtext(
"Non-recurrence mortality",
side = 3,
line = -1,
outer = TRUE,
font = 2
)
par(oldpar)
kable(round(zp_csc2$table, 3)) |>
kable_styling("striped", position = "center")
```
</details>
```{r,ph_csc2, message=FALSE, warning=FALSE,fig.align='center',echo=FALSE,eval=TRUE}
```
The statistical tests showed a potential violation of the proportional hazards assumption for nodal status in the model for non-recurrence mortality. For simplicity we ignore this violation in the remainder.
### 1.4 Examine the fit of the models
+ Cox proportional hazard model for recurrence
```{r, summary_csc1, fig.align='center',warning=FALSE}
dd <- datadist(rdata)
options(datadist = "dd")
options(prType = "html")
fit_csc1_cph <- cph(
Surv(time, status_num == 1) ~ age + size + ncat + hr_status,
x = T,
y = T,
surv = T,
data = rdata
)
print(fit_csc1_cph)
# print(summary(fit_csc1_cph))
options(datadist = NULL)
```
+ Cox proportional hazard model for non recurrence mortality
```{r, summary_csc2, fig.align='center',warning=FALSE}
dd <- datadist(rdata)
options(datadist = "dd")
options(prType = "html")
fit_csc2_cph <- cph(
Surv(time, status_num == 2) ~ age + size + ncat + hr_status,
x = T,
y = T,
surv = T,
data = rdata
)
print(fit_csc2_cph)
# print(summary(fit_csc2_cph))
options(datadist = NULL)
```
The coefficients of the models indicated that larger tumor size, positive nodal status and negative hormone receptor status status were associated with higher risk to develop a breast cancer recurrence, while older patients and larger tumors are associated with higher risk of non recurrence mortality. The associations were considered statistically significant at the usual alpha = 0.05.
### 1.5 Plot of predictors vs estimated risk at 5 years in the validation data
To get further insight into the effect of the covariates, we plot the covariate values observed in the validation set against the estimated absolute risk of breast cancer recurrence at 5 years. This gives an idea of the size of the effects.
<details>
<summary>Click to expand code</summary>
```{r, plot_risk, fig.align='center',warning=FALSE, echo=TRUE, eval=FALSE}
# Models -------------
fit_csh <- CSC(
formula = Hist(time, status_num) ~ age + size + ncat + hr_status,
data = rdata
)
# External validation at 5 years
horizon <- 5
# Calculate predicted probabilities
vdata$pred <- predictRisk(
fit_csh,
cause = 1,
newdata = vdata,
times = horizon
)
# Age
oldpar <- par(mfrow = c(2, 2))
par(xaxs = "i", yaxs = "i", las = 1)
plot(vdata$age,
vdata$pred,
bty = "n",
xlim = c(65, 100),
ylim = c(0, .6),
xlab = "Age, years",
ylab = "Estimated risk"
)
lines(
lowess(vdata$age, vdata$pred),
col = "red",
lwd = 2
)
# Size
par(xaxs = "i", yaxs = "i", las = 1)
plot(
vdata$size,
vdata$pred,
bty = "n",
xlim = c(0, 12),
ylim = c(0, .6),
xlab = "Size of tumor",
ylab = "Estimated risk"
)
lines(
lowess(vdata$size, vdata$pred),
col = "red",
lwd = 2
)
# HR status
par(xaxs = "i", yaxs = "i", las = 1)
plot(
vdata$hr_status,
vdata$pred,
ylim = c(0, .6),
bty = "n",
xlab = "Receptor status",
ylab = "Estimated risk"
)
# Nodal status
par(xaxs = "i", yaxs = "i", las = 1)
plot(
vdata$ncat,
vdata$pred,
ylim = c(0, .6),
bty = "n",
xlab = "Nodal status",
ylab = "Estimated risk"
)
par(oldpar)
```
</details>
```{r, plot_risk, fig.align='center',warning=FALSE, echo=FALSE, eval=TRUE}
```
## Goal 2 - Assessing performance of a competing risks prediction model
Here we evaluate the performance of the prediction model in terms of calibration, discrimination and overall prediction error.
### 2.1 Calibration
We assess calibration by:
- The calibration plot as a graphical representation of calibration using
the pseudo observations and the subdistribution hazard approach
- Numerical summaries of calibration:
- The observed vs expected ratio (O/E ratio) ;
- The squared bias, i.e., the average squared difference between primary event indicators and risk predictions;
- The integrated Calibration Index (ICI), i.e., the average absolute difference between primary event indicators and risk predictions;
- E50, E90 and Emax denote the median, 90th percentile and the maximum of the absolute differences between primary event indicators and risk predictions;
- Calibration intercept/slope estimated using pseudo observations:
- If on average the risk estimates equal the primary event indicators, the calibration intercept will be zero. A negative calibration intercept indicates that the risk estimates are on average too high and a positive intercept indicates that the risk estimates are on average too low.
- A calibration slope between 0 and 1 indicates overfitting of the model, i.e., too extreme predictions, both on the low and on the high end. A calibration slope >1 indicates predictions do not show enough variation.
#### 2.1.1 Calibration using pseudo observations
We calculate calibration plot and numerical summaries of calibration as
ICI, E50, E90, Emax and root squared bias using pseudo value approach.
##### 2.1.1.1 Calibration plot using pseudo observations
<details>
<summary>Click to expand code</summary>
```{r, cal, fig.align='center',warning=FALSE,message=FALSE,eval=FALSE,echo=TRUE, fig.width=5, fig.height=5}
# Models ----------
fit_csh <- CSC(Hist(time, status_num) ~
age + size +
ncat + hr_status,
data = rdata,
fitter = "cph"
)
# useful objects
primary_event <- 1 # Set to 2 if cause 2 was of interest
horizon <- 5 # Set time horizon for prediction (here 5 years)
# Predicted risk estimation
pred <- predictRisk(fit_csh,
cause = primary_event,
times = horizon,
newdata = vdata
)
# Calibration plot (pseudo-obs approach) ----------------------------------
# First compute riskRegression::Score()
score_vdata <- Score(
list("csh_validation" = fit_csh),
formula = Hist(time, status_num) ~ 1,
cens.model = "km",
data = vdata,
conf.int = TRUE,
times = horizon,
# metrics = c("auc", "brier"),
summary = c("ipa"),
cause = primary_event,
plots = "calibration"
)
calplot_pseudo <- plotCalibration(
x = score_vdata,
brier.in.legend = FALSE,
auc.in.legend = FALSE,
cens.method = "pseudo",
bandwidth = 0.05, # leave as NULL for default choice of smoothing
cex = 1,
round = FALSE, # Important, keeps all unique risk estimates rather than rounding
xlim = c(0, 0.6),
ylim = c(0, 0.6),
rug = TRUE,
xlab = "Predictions",
bty = "n"
)
title("Calibration plot using pseudo observations")
```
</details>
```{r, cal, fig.align='center',warning=FALSE,message=FALSE,eval=TRUE,echo=FALSE, fig.width=5, fig.height=5}
```
Calibration plot suggests that the prediction model seems to overestimate the observed outcome proportion of the primary event, especially at the lower and higher values of the estimated risk.
##### 2.1.1.2 Numerical summaries of calibration using pseudo observations
<details>
<summary>Click to expand code</summary>
```{r, num_cal_pseudo, fig.align='center',warning=FALSE,message=FALSE,echo=TRUE,eval=TRUE}
# We can extract predicted and observed, observed will depend on degree of smoothing (bandwidth)
dat_pseudo <- calplot_pseudo$plotFrames$csh_validation
# Calculate difference between predicted and observed (make sure to use all estimated risks, not just unique ones)
diff_pseudo <- pred - dat_pseudo$Obs[match(pred, dat_pseudo$Pred)]
# Collect all numerical summary measures
numsum_pseudo <- c(
"ICI" = mean(abs(diff_pseudo)),
setNames(quantile(abs(diff_pseudo), c(0.5, 0.9)), c("E50", "E90")),
"Emax" = max(abs(diff_pseudo)),
"Root squared bias" = sqrt(mean(diff_pseudo^2))
)
```
</details>
```{r, res_cal_pseudo, fig.align='center',warning=FALSE,message=FALSE,echo=FALSE}
# rootmeansquared, E50, E90, Emax, int, slope,
k <- 4
res_num <- rbind(
"Calibration measures - pseudo observations" = numsum_pseudo
)
res_num <- round(res_num, k)
kable(res_num) |>
kable_styling("striped", position = "center")
```
Numerical calibration measures identified overestimation of the risk especially in the higher values of the observed outcome proportion of the primary event.
#### 2.1.2 Calibration using the subdistribution hazard approach
Here we assess calibration using the subdistribution hazard approach (Austin et al.)
##### 2.1.2.1 Calibration plot using the subdistribution hazard approach
<details>
<summary>Click to expand code</summary>
```{r, plot_sd, fig.align='center',warning=FALSE,message=FALSE,eval=FALSE,echo=TRUE, fig.width=5, fig.height=5}
# Models ----------
fit_csh <- CSC(Hist(time, status_num) ~
age + size +
ncat + hr_status,
data = rdata,
fitter = "cph"
)
# useful objects
primary_event <- 1 # Set to 2 if cause 2 was of interest
horizon <- 5 # Set time horizon for prediction (here 5 years)
# Calibration plot (flexible regression approach) -------------------------
# Add estimated risk and complementary log-log of it to dataset
vdata$pred <- predictRisk(fit_csh,
cause = primary_event,
newdata = vdata,
times = horizon
)
vdata$cll_pred <- log(-log(1 - pred))
# 5 knots seems to give somewhat equivalent graph to pseudo method with bw = 0.05
n_internal_knots <- 5 # Austin et al. advise to use between 3 (more smoothing, less flexible) and 5 (less smoothing, more flexible)
rcs_vdata <- ns(vdata$cll_pred, df = n_internal_knots + 1)
colnames(rcs_vdata) <- paste0("basisf_", colnames(rcs_vdata))
vdata_bis <- cbind.data.frame(vdata, rcs_vdata)
# Use subdistribution hazards (Fine-Gray) model
form_fgr <- reformulate(
termlabels = colnames(rcs_vdata),
response = "Hist(time, status_num)"
)
# Regress subdistribution of event of interest on cloglog of estimated risks
calib_fgr <- FGR(
formula = form_fgr,
cause = primary_event,
data = vdata_bis
)
# Add observed and predicted together in a data frame
dat_fgr <- cbind.data.frame(
"obs" = predict(calib_fgr, times = horizon, newdata = vdata_bis),
"pred" = vdata$pred
)
# Calibration plot
dat_fgr <- dat_fgr[order(dat_fgr$pred), ]
par(xaxs = "i", yaxs = "i", las = 1)
plot(
x = dat_fgr$pred,
y = dat_fgr$obs,
type = "l",
xlim = c(0, 0.6),
ylim = c(0, 0.6),
xlab = "Predictions",
ylab = "Observed outcome proportion",
bty = "n"
)
abline(a = 0, b = 1, lty = "dashed", col = "red")
title("Calibration plot using subdistribution hazard approach",
cex.main = .90)
```
</details>
```{r, plot_sd, fig.align='center',warning=FALSE,message=FALSE,echo=FALSE,eval=TRUE, fig.width=5, fig.height=5}
```
Calibration plot suggests that the prediction model seems to overestimate the observed outcome proportion of the primary event, especially at the lower and higher values of the estimated risk.
##### 2.1.2.2 Numerical summaries of calibration using the subdistribution hazard approach
Here we assess calibration using the subdistribution hazard approach (Austin et al.)
<details>
<summary>Click to expand code</summary>
```{r, num_cal_sd, fig.align='center',warning=FALSE,message=FALSE,eval=FALSE, echo=TRUE}
# Numerical summary measures
diff_fgr <- dat_fgr$pred - dat_fgr$obs
numsum_fgr <- c(
"ICI" = mean(abs(diff_fgr)),
setNames(quantile(abs(diff_fgr), c(0.5, 0.9)), c("E50", "E90")),
"Emax" = max(abs(diff_fgr)),
"Root squared bias" = sqrt(mean(diff_fgr^2))
)
```
</details>
```{r, num_cal_sd, fig.align='center',warning=FALSE,message=FALSE,echo=FALSE,eval=TRUE, fig.width=5, fig.height=5}
```
```{r, num_cal_sd_out, fig.align='center',warning=FALSE,message=FALSE,echo=FALSE}
k <- 4
res_num <- rbind(
"Calibration measures - subdistribution " = numsum_fgr
)
res_num <- round(res_num, k)
kable(res_num) |>
kable_styling("striped", position = "center")
```
Numerical calibration measures identified overestimation of the risk especially in the higher values of the observed outcome proportion of the primary event.
#### 2.1.2.3 Calibration plot using pseudo-observations (LOESS smoothing)
<details>
<summary>Click to expand code</summary>
```{r loess_pseudo, echo=TRUE, eval=FALSE, fig.width=5, fig.height=5, fig.align='center'}
# Use pseudo-observations calculated by Score() (can alternatively use pseudo::pseudoci)
pseudos <- data.frame(score_vdata$Calibration$plotframe)
pseudos <- pseudos[order(pseudos$risk), ]
# Use linear loess (weighted local regression with polynomial degree = 1) smoothing
smooth_pseudos <- predict(
stats::loess(pseudovalue ~ risk, data = pseudos, degree = 1, span = 0.33),
se = TRUE
)
# Calibration plot (reported in manuscript):
# First, prepare histogram of estimated risks for x-axis
spike_bounds <- c(-0.075, 0)
bin_breaks <- seq(0, 0.6, length.out = 100 + 1)
freqs <- table(cut(pred, breaks = bin_breaks))
bins <- bin_breaks[-1]
freqs_valid <- freqs[freqs > 0]
freqs_rescaled <- spike_bounds[1] + (spike_bounds[2] - spike_bounds[1]) *
(freqs_valid - min(freqs_valid)) / (max(freqs_valid) - min(freqs_valid))
# Produce plot
par(xaxs = "i", yaxs = "i", las = 1)
plot(
x = pseudos$risk,
y = pseudos$pseudovalue,
xlim = c(0, 0.6),
ylim = c(spike_bounds[1], 0.6),
yaxt = "n",
frame.plot = FALSE,
xlab = "Estimated risks",
ylab = "Observed outcome proportions",
type = "n"
)
axis(2, seq(0, 0.6, by = 0.1), labels = seq(0, 0.6, by = 0.1))
polygon(
x = c(pseudos$risk, rev(pseudos$risk)),
y = c(
pmax(smooth_pseudos$fit - qt(0.975, smooth_pseudos$df) * smooth_pseudos$se, 0),
rev(smooth_pseudos$fit + qt(0.975, smooth_pseudos$df) * smooth_pseudos$se)
),
border = FALSE,
col = "lightgray"
)
abline(a = 0, b = 1, col = "gray")
lines(x = pseudos$risk, y = smooth_pseudos$fit, lwd = 2)
segments(
x0 = bins[freqs > 0],
y0 = spike_bounds[1],
x1 = bins[freqs > 0],
y1 = freqs_rescaled
)
```
</details>
```{r loess_pseudo, echo=FALSE, eval=TRUE, fig.width=5, fig.height=5, fig.align='center'}
```
#### 2.1.3 Observed and Expected ratio
<details>
<summary>Click to expand code</summary>
```{r, oe_ratio, fig.align='center',warning=FALSE,message=FALSE,echo=TRUE}
# Models ----------
fit_csh <- CSC(Hist(time, status_num) ~
age + size +
ncat + hr_status,
data = rdata,
fitter = "cph"
)
# useful objects
primary_event <- 1 # Set to 2 if cause 2 was of interest
horizon <- 5 # Set time horizon for prediction (here 5 years)
# Add estimated risk and complementary log-log of it to dataset
pred <- predictRisk(fit_csh,
cause = primary_event,
newdata = vdata,
times = horizon
)
## Observed/Expected ratio --------------------------------------------
# First calculate Aalen-Johansen estimate (as 'observed')
obj <- summary(survfit(Surv(time, status) ~ 1,
data = vdata
),
times = horizon
)
aj <- list(
"obs" = obj$pstate[, primary_event + 1],
"se" = obj$std.err[, primary_event + 1]
)
# Calculate O/E
OE <- aj$obs / mean(pred)
# For the confidence interval we use method proposed in Debray et al. (2017) doi:10.1136/bmj.i6460
k <- 2
alpha <- 0.05
OE_summary <- cbind(
"OE" = OE,
"Lower .95" = exp(log(OE) - qnorm(1 - alpha / 2) * aj$se / aj$obs),
"Upper .95" = exp(log(OE) + qnorm(1 - alpha / 2) * aj$se / aj$obs)
)
OE_summary <- round(OE_summary, k)
```
</details>
```{r, res_OE, echo=FALSE}
# OE, rootmeansquared, E50, E90, Emax, int, slope,
kable(OE_summary) |>
kable_styling("striped", position = "center")
```
Observed and expected ratio shown slight overestimation of the risk predicted by the model.
#### 2.1.4 Calibration intercept and slope using pseudo observations
<details>
<summary>Click to expand code</summary>
```{r, cal_intslope_pseudo, fig.align='center',warning=FALSE,message=FALSE, echo=TRUE}
# Models ----------
fit_csh <- CSC(Hist(time, status_num) ~
age + size +