-
Notifications
You must be signed in to change notification settings - Fork 11
/
coxph-model-building.qmd
1716 lines (1327 loc) · 43 KB
/
coxph-model-building.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Building Cox Proportional Hazards models
### `hodg` Lymphoma Data Set from `KMsurv`
#### Participants
43 bone marrow transplant patients at Ohio State University (Avalos
1993)
#### Variables
- `dtype`: Disease type (Hodgkin's or non-Hodgkins lymphoma)
- `gtype`: Bone marrow graft type:
- allogeneic: from HLA-matched sibling
- autologous: from self (prior to chemo)
- `time`: time to study exit
- `delta`: study exit reason (death/relapse vs censored)
- `wtime`: waiting time to transplant (in months)
- `score`: Karnofsky score:
- 80--100: Able to carry on normal activity and to work; no special
care needed.
- 50--70: Unable to work; able to live at home and care for most
personal needs; varying amount of assistance needed.
- 10--60: Unable to care for self; requires equivalent of
institutional or hospital care; disease may be progressing rapidly.
#### Data
```{r}
data(hodg, package = "KMsurv")
hodg2 = hodg |>
as_tibble() |>
mutate(
# We add factor labels to the categorical variables:
gtype = gtype |>
case_match(
1 ~ "Allogenic",
2 ~ "Autologous"),
dtype = dtype |>
case_match(
1 ~ "Non-Hodgkins",
2 ~ "Hodgkins") |>
factor() |>
relevel(ref = "Non-Hodgkins"),
delta = delta |>
case_match(
1 ~ "dead",
0 ~ "alive"),
surv = Surv(
time = time,
event = delta == "dead")
)
hodg2 |> print()
```
### Proportional hazards model
```{r}
hodg.cox1 = coxph(
formula = surv ~ gtype * dtype + score + wtime,
data = hodg2)
summary(hodg.cox1)
```
::: content-hidden
```{r}
### fancier alternatives:
# library(parameters)
# hodg.cox1 |>
# parameters() |>
# print_md()
# library(gtsummary)
# hodg.cox1 |>
# tbl_regression() |>
# as_hux_table()
```
:::
## Diagnostic graphs for proportional hazards assumption
### Analysis plan
- **survival function** for the four combinations of disease type and
graft type.
- **observed (nonparametric) vs. expected (semiparametric) survival**
functions.
- **complementary log-log survival** for the four groups.
### Kaplan-Meier survival functions
```{r}
#| fig-cap: "Kaplan-Meier Survival Curves for HOD/NHL and Allo/Auto Grafts"
km_model = survfit(
formula = surv ~ dtype + gtype,
data = hodg2)
km_model |>
autoplot(conf.int = FALSE) +
theme_bw() +
theme(
legend.position="bottom",
legend.title = element_blank(),
legend.text = element_text(size = legend_text_size)
) +
guides(col=guide_legend(ncol=2)) +
ylab('Survival probability, S(t)') +
xlab("Time since transplant (days)")
```
### Observed and expected survival curves
```{r}
#| fig-cap: "Observed and Expected Survival Curves"
# we need to create a tibble of covariate patterns;
# we will set score and wtime to mean values for disease and graft types:
means = hodg2 |>
summarize(
.by = c(dtype, gtype),
score = mean(score),
wtime = mean(wtime)) |>
arrange(dtype, gtype) |>
mutate(strata = paste(dtype, gtype, sep = ",")) |>
as.data.frame()
# survfit.coxph() will use the rownames of its `newdata`
# argument to label its output:
rownames(means) = means$strata
cox_model =
hodg.cox1 |>
survfit(
data = hodg2, # ggsurvplot() will need this
newdata = means)
```
```{r}
# I couldn't find a good function to reformat `cox_model` for ggplot,
# so I made my own:
stack_surv_ph = function(cox_model)
{
cox_model$surv |>
as_tibble() |>
mutate(time = cox_model$time) |>
pivot_longer(
cols = -time,
names_to = "strata",
values_to = "surv") |>
mutate(
cumhaz = -log(surv),
model = "Cox PH")
}
km_and_cph =
km_model |>
fortify(surv.connect = TRUE) |>
mutate(
strata = trimws(strata),
model = "Kaplan-Meier",
cumhaz = -log(surv)) |>
bind_rows(stack_surv_ph(cox_model))
```
```{r}
#| fig-cap: "Observed and expected survival curves for `bmt` data"
km_and_cph |>
ggplot(aes(x = time, y = surv, col = model)) +
geom_step() +
facet_wrap(~strata) +
theme_bw() +
ylab("S(t) = P(T>=t)") +
xlab("Survival time (t, days)") +
theme(legend.position = "bottom")
```
::: content-hidden
```{r}
# these are some old-style R plots inherited from Prof. Rocke's notes;
# they should be updated to ggplot2-style plots eventually:
par(mfrow = c(2,2), mai = rep(0.5, 4)) # set up a multipanel panel
plot(km_model[1],xlim=c(0,600),col=1:4,lwd=2, conf.int = FALSE,
main = "NHL Allogeneic", lty = 1)
lines(cox_model[1],lwd= 2,lty=2, col = 2, conf.int = FALSE)
legend("bottomleft",c("K-M", "Cox PH"),col=1:2,lwd=1:2)
plot(km_model[2],xlim=c(0,600),col=1:4,lwd=2, conf.int = FALSE,
main = "NHL Autologous", lty = 1)
lines(cox_model[2],lwd= 2,lty=2, col = 2, conf.int = FALSE)
plot(km_model[3],xlim=c(0,600),col=1:4,lwd=2, conf.int = FALSE,
main = "HL Allogeneic", lty = 1)
lines(cox_model[3],lwd= 2,lty=2, col = 2, conf.int = FALSE)
plot(
km_model[4],
xlim=c(0,600),
col=1:4,
lwd=2,
conf.int = FALSE,
main = "HL Autologous",
lty = 1)
lines(
cox_model[4],
lwd= 2,
lty=2,
col = 2,
conf.int = FALSE)
par(mfrow = c(1,1)) # reset the paneling
```
```{r}
#| label: survminer-1
temp1 =
km_model |>
survminer::ggsurvplot(
legend = "bottom",
legend.title = "",
combine = TRUE,
fun = 'pct',
size = .5,
ggtheme = theme_bw(),
conf.int = FALSE,
censor = FALSE) |>
suppressWarnings() # ggsurvplot() throws some warnings that aren't too worrying
temp2 =
cox_model |>
survminer::ggsurvplot(
legend = "bottom",
legend.title = "",
combine = TRUE,
fun = 'pct',
size = .5,
ggtheme = theme_bw(),
conf.int = FALSE,
censor = FALSE) |>
suppressWarnings()
temp =
list(KM = km_model,
Cox = cox_model) |>
survminer::ggsurvplot(
# facet.by = gtype,
legend = "bottom",
legend.title = "",
combine = TRUE,
fun = 'pct',
size = .5,
ggtheme = theme_bw(),
conf.int = FALSE,
censor = FALSE) |>
suppressWarnings() # ggsurvplot() throws some warnings that aren't too worrying
```
:::
### Cumulative hazard (log-scale) curves
Also known as "complementary log-log (clog-log) survival curves".
```{r}
#| label: fig-cloglog-na
#| fig-cap: "Complementary log-log survival curves - Nelson-Aalen estimates"
na_model = survfit(
formula = surv ~ dtype + gtype,
data = hodg2,
type = "fleming")
na_model |>
survminer::ggsurvplot(
legend = "bottom",
legend.title = "",
ylab = "log(Cumulative Hazard)",
xlab = "Time since transplant (days, log-scale)",
fun = 'cloglog',
size = .5,
ggtheme = theme_bw(),
conf.int = FALSE,
censor = TRUE) |>
magrittr::extract2("plot") +
guides(
col =
guide_legend(
ncol = 2,
label.theme =
element_text(
size = legend_text_size)))
```
Let's compare these empirical (i.e., non-parametric) curves with the
fitted curves from our `coxph()` model:
```{r}
#| label: fig-cloglog-ph
#| fig-cap: "Complementary log-log survival curves - PH estimates"
cox_model |>
survminer::ggsurvplot(
facet_by = "",
legend = "bottom",
legend.title = "",
ylab = "log(Cumulative Hazard)",
xlab = "Time since transplant (days, log-scale)",
fun = 'cloglog',
size = .5,
ggtheme = theme_bw(),
censor = FALSE, # doesn't make sense for cox model
conf.int = FALSE) |>
magrittr::extract2("plot") +
guides(
col =
guide_legend(
ncol = 2,
label.theme =
element_text(
size = legend_text_size)))
```
Now let's overlay these cumulative hazard curves:
```{r}
#| label: fig-bmt-cumhaz
#| fig-cap: "Observed and expected cumulative hazard curves for `bmt` data (cloglog format)"
na_and_cph =
na_model |>
fortify(fun = "cumhaz") |>
# `fortify.survfit()` doesn't name cumhaz correctly:
rename(cumhaz = surv) |>
mutate(
surv = exp(-cumhaz),
strata = trimws(strata)) |>
mutate(model = "Nelson-Aalen") |>
bind_rows(stack_surv_ph(cox_model))
na_and_cph |>
ggplot(
aes(
x = time,
y = cumhaz,
col = model)) +
geom_step() +
facet_wrap(~strata) +
theme_bw() +
scale_y_continuous(
trans = "log10",
name = "Cumulative hazard H(t) (log-scale)") +
scale_x_continuous(
trans = "log10",
name = "Survival time (t, days, log-scale)") +
theme(legend.position = "bottom")
```
## Predictions and Residuals
### Review: Predictions in Linear Regression
- In linear regression, we have a linear predictor for each data point
$i$
$$
\begin{aligned}
\eta_i &= \beta_0+\beta_1x_{1i}+\cdots+\beta_px_{pi}\\
\hat y_i &=\hat\eta_i = \hat\beta_0+\hat\beta_1x_{1i}+\cdots+\hat\beta_px_{pi}\\
y_i &\sim N(\eta_i,\sigma^2)
\end{aligned}
$$
- $\hat y_i$ estimates the conditional mean of $y_i$ given the
covariate values $\vx_i$. This together with the prediction
error says that we are predicting the distribution of values of $y$.
### Review: Residuals in Linear Regression
- The usual residual is $r_i=y_i-\hat y_i$, the difference between the
actual value of $y$ and a prediction of its mean.
- The residuals are also the quantities the sum of whose squares is
being minimized by the least squares/MLE estimation.
### Predictions and Residuals in survival models
- In survival analysis, the equivalent of $y_i$ is the event time
$t_i$, which is unknown for the censored observations.
- The expected event time can be tricky to calculate:
$$
\hat{\text{E}}[T|X=x] = \int_{t=0}^{\infty} \hat S(t)dt
$$
### Wide prediction intervals
The nature of time-to-event data results in very wide prediction
intervals:
- Suppose a cancer patient is predicted to have a mean lifetime of 5
years after diagnosis and suppose the distribution is exponential.
- If we want a 95% interval for survival, the lower end is at the
0.025 percentage point of the exponential which is
`qexp(.025, rate = 1/5)` = `r qexp(.025, rate = 1/5)` years, or 1/40
of the mean lifetime.
- The upper end is at the 0.975 point which is
`qexp(.975, rate = 1/5)` = `r qexp(.975, rate = 1/5)` years, or 3.7
times the mean lifetime.
- Saying that the survival time is somewhere between 6 weeks and 18
years does not seem very useful, but it may be the best we can do.
- For survival analysis, something is like a residual if it is small
when the model is accurate or if the accumulation of them is in some
way minimized by the estimation algorithm, but there is no exact
equivalence to linear regression residuals.
- And if there is, they are mostly quite large!
### Types of Residuals in Time-to-Event Models
- It is often hard to make a decision from graph appearances, though
the process can reveal much.
- Some diagnostic tests are based on residuals as with other
regression methods:
- **Schoenfeld residuals** (via `cox.zph`) for proportionality
- **Cox-Snell residuals** for goodness of fit (@sec-cox-snell)
- **martingale residuals** for non-linearity
- **dfbeta** for influence.
::: content-hidden
### Martingale and deviance residuals
For martingale and deviance residuals, the returned object is a vector
with one element for each subject (without collapse). Even censored
observations have a martingale residual and a deviance residual. Each
subject's value for the martingale residual and the deviance residual is
a single value.
### Score residuals
Each observation also has a score residual, though this is a vector, not
a scalar.
For score residuals the returned object is a matrix with one row per
subject and one column per variable. The row order will match the input
data for the original fit.
The score residuals are each individual's contribution to the score
vector: $\ell'(\beta;y_i)$
- For Schoenfeld residuals, the returned object is a matrix with one
row for each event and one column per variable.
- The rows are ordered by time within strata, and an attribute
**strata** is attached that contains the number of observations in
each stratum.
- The scaled Schoenfeld residuals are used in the `cox.zph()`
function.
- Only subjects with an observed event time have a Schoenfeld
residual, which like the score residual is a vector.
:::
### Schoenfeld residuals
- There is a Schoenfeld residual for each subject $i$ with an event
(not censored) and for each predictor $x_{k}$.
- At the event time $t$ for that subject, there is a risk set $R$, and
each subject $j$ in the risk set has a risk coefficient $\theta_j$
and also a value $x_{jk}$ of the predictor.
- The Schoenfeld residual is the difference between $x_{ik}$ and the
risk-weighted average of all the $x_{jk}$ over the risk set.
$$
r^S_{ik} =
x_{ik}-\frac{\sum_{k\in R}x_{jk}\theta_k}{\sum_{k\in R}\theta_k}
$$
This residual measures how typical the individual subject is with
respect to the covariate at the time of the event. Since subjects should
fail more or less uniformly according to risk, the Schoenfeld residuals
should be approximately level over time, not increasing or decreasing.
We can test this with the correlation with time on some scale, which
could be the time itself, the log time, or the rank in the set of
failure times.
The default is to use the KM curve as a transform, which is similar to
the rank but deals better with censoring.
The `cox.zph()` function implements a score test proposed in @grambsch1994proportional.
```{r}
hodg.zph = cox.zph(hodg.cox1)
print(hodg.zph)
```
#### `gtype`
```{r}
ggcoxzph(hodg.zph, var = "gtype")
```
#### `dtype`
```{r}
ggcoxzph(hodg.zph, var = "dtype")
```
#### `score`
```{r}
ggcoxzph(hodg.zph, var = "score")
```
#### `wtime`
```{r}
ggcoxzph(hodg.zph, var = "wtime")
```
#### `gtype:dtype`
```{r}
ggcoxzph(hodg.zph, var = "gtype:dtype")
```
#### Conclusions
- From the correlation test, the Karnofsky score and the interaction
with graft type disease type induce modest but statistically
significant non-proportionality.
- The sample size here is relatively small (26 events in 43 subjects).
If the sample size is large, very small amounts of
non-proportionality can induce a significant result.
- As time goes on, autologous grafts are over-represented at their own
event times, but those from HOD patients become less represented.
- Both the statistical tests and the plots are useful.
## Goodness of Fit using the Cox-Snell Residuals {#sec-cox-snell}
(references: @klein2003survival, §11.2, and @dobson4e, §10.6)
---
::: notes
Suppose that an individual has a survival time $T$ which has survival
function $S(t)$, meaning that $\Pr(T> t) = S(t)$. Then $S(T)$ has a
uniform distribution on $(0,1)$:
:::
$$
\begin{aligned}
\Pr(S(T_i) \le u)
&= \Pr(T_i > S_i^{-1}(u))\\
&= S_i(S_i^{-1}(u))\\
&= u
\end{aligned}
$$
---
::: notes
Also, if $U$ has a uniform distribution on $(0,1)$, then what is the
distribution of $-\ln(U)$?
:::
---
$$
\begin{aligned}
\Pr(-\ln(U) < x) &= \Pr(U>\exp{-x})\\
&= 1-e^{-x}
\end{aligned}
$$
::: notes
which is the CDF of an exponential distribution with parameter
$\lambda=1$.
:::
---
:::{#def-CS-resid}
#### Cox-Snell generalized residuals
::: notes
The **Cox-Snell generalized residuals** are defined as:
:::
$$
r^{CS}_i \eqdef \hat H(t_i|\vx_i)
$$
:::
::: notes
If the estimate $\hat S_i$ is accurate, $r^{CS}_i$
should have an exponential distribution with constant hazard $\lambda=1$,
which means that these values
should look like a censored sample from this exponential distribution.
:::
---
```{r}
#| fig-cap: "Cumulative Hazard of Cox-Snell Residuals"
hodg2 = hodg2 |>
mutate(cs = predict(hodg.cox1, type = "expected"))
surv.csr = survfit(
data = hodg2,
formula = Surv(time = cs, event = delta == "dead") ~ 1,
type = "fleming-harrington")
autoplot(surv.csr, fun = "cumhaz") +
geom_abline(aes(intercept = 0, slope = 1), col = "red") +
theme_bw()
```
The line with slope 1 and intercept 0 fits the curve relatively well, so
we don't see lack of fit using this procedure.
## Martingale Residuals
The **martingale residuals** are a slight modification of the Cox-Snell
residuals. If the censoring indicator is $\delta_i$, then
$$r^M_i=\delta_i-r^{CS}_i$$ These residuals can be interpreted as an
estimate of the excess number of events seen in the data but not
predicted by the model. We will use these to examine the functional
forms of continuous covariates.
::: content-hidden
### Martingale
Originally, a martingale referred to a betting strategy where you bet
\$1 on the first play, then you double the bet if you lose and continue
until you win. This seems like a sure thing, because at the end of each
series when you finally win, you are up \$1. For example,
$-1-2-4-8+16=1$. But this assumes that you have infinite resources.
Really, you have a large probability of winning \$1, and a small
probability of losing everything you have, kind of the opposite of a
lottery.
martingale
: In probability, a **martingale** is a sequence of random variables
such that the expected value of the next event at any time is the
present observed value, and that no better predictor can be derived
even with all past values of the series available. At least to a
close approximation, the stock market is a martingale. Under the
assumptions of the proportional hazards model, the martingale
residuals ordered in time form a martingale.
:::
### Using Martingale Residuals
Martingale residuals can be used to examine the functional form of a
numeric variable.
- We fit the model without that variable and compute the martingale
residuals.
- We then plot these martingale residuals against the values of the
variable.
- We can see curvature, or a possible suggestion that the variable can
be discretized.
Let's use this to examine the `score` and `wtime` variables in the
`wtime` data set.
#### Karnofsky score {.unnumbered}
```{r}
#| fig-cap: "Martingale Residuals vs. Karnofsky Score"
hodg2 = hodg2 |>
mutate(
mres =
hodg.cox1 |>
update(. ~ . - score) |>
residuals(type="martingale"))
hodg2 |>
ggplot(aes(x = score, y = mres)) +
geom_point() +
geom_smooth(method = "loess", aes(col = "loess")) +
geom_smooth(method = 'lm', aes(col = "lm")) +
theme_classic() +
xlab("Karnofsky Score") +
ylab("Martingale Residuals") +
guides(col=guide_legend(title = ""))
```
The line is almost straight. It could be some modest transformation of
the Karnofsky score would help, but it might not make much difference.
#### Waiting time {.unnumbered}
```{r}
#| fig-cap: "Martingale Residuals vs. Waiting Time"
hodg2$mres =
hodg.cox1 |>
update(. ~ . - wtime) |>
residuals(type="martingale")
hodg2 |>
ggplot(aes(x = wtime, y = mres)) +
geom_point() +
geom_smooth(method = "loess", aes(col = "loess")) +
geom_smooth(method = 'lm', aes(col = "lm")) +
theme_classic() +
xlab("Waiting Time") +
ylab("Martingale Residuals") +
guides(col=guide_legend(title = ""))
```
The line could suggest a step function. To see where the drop is, we can
look at the largest waiting times and the associated martingale
residual.
The martingale residuals are all negative for `wtime` \>83 and positive
for the next smallest value. A reasonable cut-point is 80 days.
#### Updating the model {.unnumbered}
Let's reformulate the model with dichotomized `wtime`.
```{r}
hodg2 =
hodg2 |>
mutate(
wt2 = cut(
wtime,c(0, 80, 200),
labels=c("short","long")))
hodg.cox2 =
coxph(
formula =
Surv(time, event = delta == "dead") ~
gtype*dtype + score + wt2,
data = hodg2)
```
```{r}
#| tbl-cap: "Model summary table with waiting time on continuous scale"
hodg.cox1 |> drop1(test="Chisq")
```
```{r}
#| tbl-cap: "Model summary table with dichotomized waiting time"
hodg.cox2 |> drop1(test="Chisq")
```
The new model has better (lower) AIC.
## Checking for Outliers and Influential Observations
We will check for outliers using the deviance residuals. The martingale
residuals show excess events or the opposite, but highly skewed, with
the maximum possible value being 1, but the smallest value can be very
large negative. Martingale residuals can detect unexpectedly long-lived
patients, but patients who die unexpectedly early show up only in the
deviance residual. Influence will be examined using dfbeta in a similar
way to linear regression, logistic regression, or Poisson regression.
### Deviance Residuals
$$
\begin{aligned}
r_i^D &= \textrm{sign}(r_i^M)\sqrt{-2\left[ r_i^M+\delta_i\ln(\delta_i-r_i^M) \right]}\\
r_i^D &= \textrm{sign}(r_i^M)\sqrt{-2\left[ r_i^M+\delta_i\ln(r_i^{CS}) \right]}
\end{aligned}
$$
Roughly centered on 0 with approximate standard deviation 1.
###
```{r}
hodg.mart = residuals(hodg.cox2,type="martingale")
hodg.dev = residuals(hodg.cox2,type="deviance")
hodg.dfb = residuals(hodg.cox2,type="dfbeta")
hodg.preds = predict(hodg.cox2) #linear predictor
```
```{r}
#| fig-cap: "Martingale Residuals vs. Linear Predictor"
plot(hodg.preds,
hodg.mart,
xlab="Linear Predictor",
ylab="Martingale Residual")
```
The smallest three martingale residuals in order are observations 1, 29,
and 18.
```{r}
#| fig-cap: "Deviance Residuals vs. Linear Predictor"
plot(hodg.preds,hodg.dev,xlab="Linear Predictor",ylab="Deviance Residual")
```
The two largest deviance residuals are observations 1 and 29. Worth
examining.
### dfbeta
- dfbeta is the approximate change in the coefficient vector if that
observation were dropped
- dfbetas is the approximate change in the coefficients, scaled by the
standard error for the coefficients.
#### Graft type
```{r}
#| fig-cap: "dfbeta Values by Observation Order for Graft Type"
plot(hodg.dfb[,1],xlab="Observation Order",ylab="dfbeta for Graft Type")
```
The smallest dfbeta for graft type is observation 1.
#### Disease type
```{r}
#| fig-cap: "dfbeta Values by Observation Order for Disease Type"
plot(hodg.dfb[,2],
xlab="Observation Order",
ylab="dfbeta for Disease Type")
```
The smallest two dfbeta values for disease type are observations 1 and
16.
#### Karnofsky score
```{r}
#| fig-cap: "dfbeta Values by Observation Order for Karnofsky Score"
plot(hodg.dfb[,3],
xlab="Observation Order",
ylab="dfbeta for Karnofsky Score")
```
The two highest dfbeta values for score are observations 1 and 18. The
next three are observations 17, 29, and 19. The smallest value is
observation 2.
#### Waiting time (dichotomized)
```{r}
#| fig-cap: "dfbeta Values by Observation Order for Waiting Time (dichotomized)"
plot(
hodg.dfb[,4],
xlab="Observation Order",
ylab="dfbeta for `Waiting Time < 80`")
```
The two large values of dfbeta for dichotomized waiting time are
observations 15 and 16. This may have to do with the discretization of
waiting time.
#### Interaction: graft type and disease type
```{r}
#| fig-cap: "dfbeta Values by Observation Order for dtype:gtype"
plot(hodg.dfb[,5],
xlab="Observation Order",
ylab="dfbeta for dtype:gtype")
```
The two largest values are observations 1 and 16. The smallest value is observation 35.
| Diagnostic | Observations to Examine |
|----------------------------|-------------------------|
| Martingale Residuals | 1, 29, 18 |
| Deviance Residuals | 1, 29 |
| Graft Type Influence | 1 |
| Disease Type Influence | 1, 16 |
| Karnofsky Score Influence | 1, 18 (17, 29, 19) |
| Waiting Time Influence | 15, 16 |
| Graft by Disease Influence | 1, 16, 35 |
: Observations to Examine by Residuals and Influence {#tbl-obs-to-examine}
The most important observations to examine seem to be 1, 15, 16, 18, and
29.
###
```{r}
with(hodg,summary(time[delta==1]))
```
```{r}
with(hodg,summary(wtime))
```
```{r}
with(hodg,summary(score))
```
```{r}
hodg.cox2
```
```{r}
hodg2[c(1,15,16,18,29),] |>
select(gtype, dtype, time, delta, score, wtime) |>
mutate(
comment =
c(
"early death, good score, low risk",
"high risk grp, long wait, poor score",
"high risk grp, short wait, poor score",
"early death, good score, med risk grp",
"early death, good score, med risk grp"
))
```
### Action Items
- Unusual points may need checking, particularly if the data are not
completely cleaned. In this case, observations 15 and 16 may show
some trouble with the dichotomization of waiting time, but it still
may be useful.
- The two largest residuals seem to be due to unexpectedly early
deaths, but unfortunately this can occur.
- If hazards don't look proportional, then we may need to use strata,
between which the base hazards are permitted to be different. For
this problem, the natural strata are the two diseases, because they
could need to be managed differently anyway.
- A main point that we want to be sure of is the relative risk
difference by disease type and graft type.
```{r}
#| tbl-cap: "Linear Risk Predictors for Lymphoma"
hodg.cox2 |>
predict(
reference = "zero",
newdata = means |>
mutate(
wt2 = "short",
score = 0),
type = "lp") |>
data.frame('linear predictor' = _) |>
pander()
```
For Non-Hodgkin's, the allogenic graft is better. For Hodgkin's, the
autologous graft is much better.
## Stratified survival models
### Revisiting the leukemia dataset (`anderson`)
We will analyze remission survival times on 42 leukemia patients, half
on new treatment, half on standard treatment.
This is the same data as the `drug6mp` data from `KMsurv`, but with two
other variables and without the pairing. This version comes from @kleinbaum2012survival (e.g., p281):
```{r,include = FALSE}
anderson =
fs::path_package(
"rme", "extdata/anderson.dta") |>
haven::read_dta() |>
mutate(
status = status |>
case_match(
1 ~ "relapse",
0 ~ "censored"
),