-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathslides.Rmd
1823 lines (1364 loc) · 47.3 KB
/
slides.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: "Wrangling Survival Data"
subtitle: "From Time-dependent Covariates to Multistate Endpoints"
date: "Beth Atkinson \n September 12, 2019"
output:
beamer_presentation:
toc: false
slide_level: 2
template: template.tex
includes:
in_header: preamble.tex
section-title-slides: true
---
```{r setup, include=FALSE}
library(knitr)
library(survival)
library(survminer)
library(tidyverse)
library(hexbin)
options(stringsAsFactors=F,
contrasts=c("contr.treatment","contr.poly"),
show.signif.stars = FALSE,
continue=" ", width=60)
opts_chunk$set(echo=FALSE, message=FALSE, warning=FALSE, collapse=TRUE,
prompt=TRUE, cache=FALSE, comment=NA, tidy=FALSE,
out.width="90%", out.height="!")
plotTheme <- theme_bw() +
theme(plot.title = element_text(size = 20),
strip.text = element_text(size=18),
axis.text = element_text(size=15),
axis.title = element_text(size=18),
legend.text=element_text(size=15),
legend.title=element_text(size=18))
```
## Outline
* Time to event - one observation per subject
* Start/Stop data
+ Why needed?
+ New tools: `tmerge`, `survSplit`
+ Check data: `survcheck`
+ Common mistakes
* Multistate data
+ Competing risk
# Basics
## Logistics
* All code shown based on the latest/greatest version of the `survival` package (3.0)
* Slides/Example code available at https://github.com/bethatkinson/rmed2019_surv
+ Examples loaded into RStudio Cloud - https://rstudio.cloud/project/475200
* Email: atkinson@mayo.edu
```{r out.width = "20%"}
include_graphics('figures/logo.png')
```
## Background
* I am a statistician working in medical research
* Many of the questions I work with are "time until ..."
+ Fracture
+ Diagnosis of a chronic comorbidity
+ Liver transplant
+ Death
+ ...
* I study osteoporosis in population-based cohorts, so many of my examples deal with fractures
* I started off using Splus in 1990 so my code is a mix of base R and tidyverse
## Premise
Most statistics discussions focus on the analysis and assume the data is already in shape. The reality is that:
* Data wrangling takes much of the time
* Doing it correctly is critical
* ... so that's what I'll talk about
## Some principles of data creation
* Correct is more important than fast: Don't worry if the code takes a bit to run. We often do dozens of fits using one dataset
* Correct is more important than clever
* Readable is more important than short
* Use every data check opportunity available
* Comments are your friend, or better yet make the data creation an Rmd file with text explaining the code
## Key Principle
"It takes time to observe time"
Challenges:
* Incomplete information (*censoring*). At the time of an analysis, not everyone will have yet had the event.
* Dated results.
+ In order to report 5 year survival, from a
treatment, patients need to be enrolled and then followed for 5+ years.
+ By the time recruitment and follow-up is finished,
the final report on the treatment might be 8
years old and considered out of date.
## Calendar Year Scale
```{r mkdata, echo=FALSE}
date1 <- c(1995.1, 1996.5, 1997.2, 1997.8, 1998.0,
1999.3, 2001.4, 2002.1, 2002.8, 2003.7,
2004.0, 2006.6, 2007.3, 2008.0, 2009.9,
2010.2, 2011.6, 2012.1, 2013.5, 2014.8)
date1 <- date1[c(2, 15, 20, 8, 19,
18,17,16,5,14,
13,12,10,11,9,
7,6,4,3,1)]
time1 <- c(1,2,2,3,4, 4,5,5,8,8, 9,10, 11, 12, 14, 15, 16, 16, 18, 20)
event1 <-c(1,1,2,1,0,2,1,2,1,1,1, 0,2,1,2,0,1,2,1,0)
set.seed(02846)
rand <- runif(20)
date2 <- date1[order(rand)]
time2 <- time1[order(rand)]
event2 <- event1[order(rand)]
pchtype2 <- sample(0:1, 20, replace=T)
# Figure 1
# plot raw data - date scale
tmpdat <- data.frame(subj=20:1, Endpoint=factor(pchtype2, levels=0:1,
labels=c('Censor','Event')),
futime=time2, date1=date2, date2=date2+time2)
## create treated Y/N
set.seed(2)
tmpdat$treated <- factor(sample(1:2, size=20, replace=T), levels=1:2, labels=c('N','Y'))
## Create start time for time-dependent covariate
time3 <- tmpdat$futime
for(i in 1:length(time3)) time3[i] <- sample(0:tmpdat$futime[i],1)
tmpdat$time3 <- time3
# create time4 for multiple events
set.seed(2)
tmpdat$pchtype3 <- sample(c('','X'), 20, replace=T)
time4 <- tmpdat$futime
for(i in 1:length(tmpdat$futime)) time4[i] <- sample(1:(tmpdat$futime[i]-1),1)
tmpdat$time4 <- time4
## create time5 for left truncation
set.seed(10)
tmpdat$time5 <- tmpdat$time3
tmpdat$time5[tmpdat$time5==tmpdat$futime] <- 0
## create time to end gap
tmpdat$time6 <- tmpdat$time4 + runif(n=nrow(tmpdat), min=.2, max=5.2)
```
```{r}
## first version of plot - on date scale
ggplot(tmpdat, aes(date1,subj)) +
geom_segment(data=tmpdat,aes(x=date1,y=subj,xend=date2,yend=subj), size=1) +
plotTheme + geom_point(data=tmpdat, aes(x=date2, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Date") + ylab("Subject")
```
## Time from Study Entry Scale
```{r, echo=FALSE}
# rescale to time-since-diagnosis scale
ggplot(tmpdat, aes(futime,subj)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=futime,yend=subj), size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint), size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Study Entry, years") + ylab("Subject")
```
## Compare Baseline Treatment Groups
```{r, echo=FALSE}
# time-since-diagnosis - add color for baseline treatment
ggplot(tmpdat, aes(futime,subj, color=treated)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Study Entry, years") + ylab("Subject")
```
## Example: AML data
Does maintainance of the standard course of chemotherapy improve survival for patients with Acute Myelogeous Leukemia?
```{r, echo=TRUE}
dim(aml)
head(aml)
```
## Create endpoint in `survival` package
A time-to-event outcome consists of 2 pieces of information:
* Length of time over which the patient was observed
* Presence/absence of the event at the end of the time period
+ 0=censor/1=event
+ FALSE=censor/TRUE=event
+ 1=censor/2=event
```{r echo=T, eval=T}
with(aml, Surv(time=time, event=status))[1:6]
aml$status[1:6]
```
## Kaplan-Meier Curves: default
```{r, echo=TRUE, fig.show='hide'}
fit <- survfit(Surv(time, status) ~ x, data=aml)
print(fit)
plot(fit,
xlab='Time since enrollment, months',
ylab='Survival probability')
```
##
```{r}
plot(fit, lwd=2,
xlab='Time since enrollment, months',
ylab='Survival probability')
title('Default Plot')
```
## Kaplan-Meier Curves: better
```{r, echo=TRUE, fig.show='hide'}
print(fit, scale=12)
plot(fit, xscale=12, xlim=c(0, 4*12),
col=1:2, lty=1:2,
xlab='Time since enrollment, years',
ylab='Survival probability')
legend('topright', legend=names(fit$strata),
col=1:2, lty=1:2, bty='n')
```
##
```{r}
plot(fit, xscale=12, xlim=c(0, 4*12),
col=1:2, lty=1:2, lwd=2,
xlab='Time since enrollment, years',
ylab='Survival probability')
legend('topright', legend=names(fit$strata),
col=1:2, lty=1:2, bty='n')
title('Better')
```
## Kaplan-Meier Curves: ggsurvplot
```{r, echo=TRUE, fig.show='hide'}
library(survminer)
ggsurvplot(fit, xscale=12, xlim=c(0, 4*12),
censor=FALSE, break.x.by=12,
risk.table=TRUE,
xlab='Time since enrollment, years',
ylab='Survival probability')
```
##
```{r}
ggsurvplot(fit, xscale=12, xlim=c(0,4*12),
censor=FALSE, break.x.by=12,
risk.table=TRUE,
xlab='Time since enrollment, years',
ylab='Survival probability',
title='ggsurvplot')
```
##
```{r}
par(cex=.9, mai=c(.8,1.2,.5,.1))
par(fig=c(x1=0,x2=1,y1=.2,y2=1))
plot(fit, xscale=12, xlim=c(0, 4*12),
col=1:2, lty=1:2, lwd=2,
xlab='Time since enrollment, years',
ylab='Survival probability')
title('Base R, risk table')
legend('topright', legend=names(fit$strata),
col=1:2, lty=1:2, bty='n')
par(fig=c(0,1,0,.2), new=TRUE, mai=c(.1,1.2,0,.1))
tmp <- summary(fit, times=c(0:4)*12)
plot(c(0,4),c(0,4), axes=FALSE, pch='', xlab='', ylab='', xlim=c(0,4))
text(x=c(tmp$time/12,4), y=rep(2:1, each=5), labels=c(tmp$n.risk,0))
axis(2, at=2:1, c('Maintained','Nonmaintained'), las=1, lty=0)
par(mai=c(1.02,.82,.82,.42), fig=c(0,1,0,1))
```
## Cox Models
```{r, echo=TRUE}
fit <- coxph(Surv(time, status) ~ x, data=aml)
fit
```
## \textcolor{yellow}{Your Turn - Run basic analysis}
* See exercises/1.basic_survival.Rmd
# Start/Stop Data
## Use Cases
When is start/stop data needed?
* Time-dependent covariates
* Multiple events of the same type per subject
* Left truncation or gaps in observation
* Analysis by time periods
* Multistate
*=>* Deceptively simple task, easy to do incorrectly
## Time-Dependent Covariates
```{r, echo=FALSE}
ggplot(tmpdat, aes(futime,subj, color=treated)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=time3,yend=subj), color="#F8766D",size=1) +
geom_segment(data=tmpdat,aes(x=time3, y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Diagnosis, years") + ylab("Subject")
```
## Time-Dependent Covariates
* Lab values that change over time (`pbcseq` data)
* Medication
+ Ever exposed
+ Cumulative dose
+ On and off
* Diagnosis of new comorbidity (e.g., diabetes)
* Surgery
## Multiple Events/Same Type
```{r, echo=FALSE}
ggplot(tmpdat, aes(futime,subj)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Diagnosis, years") + ylab("Subject") +
geom_point(data=tmpdat, aes(x=time4, y=subj), shape=tmpdat$pchtype3, size=4)
```
## Multiple Events/Same Type
* Fractures
* Repeat infections (`rhDNase`, `cgd` data)
* Number of recurrences of cancer (`bladder` data)
## Left Truncation
```{r, echo=FALSE}
ggplot(tmpdat, aes(futime,subj)) +
geom_segment(data=tmpdat,aes(x=time5, y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Diagnosis, years") + ylab("Subject")
```
## Left Truncation
* Disease started prior to diagnosis, want time-scale to be time-since-onset
* Population-based cohort, interested in "age" as a time-scale
## Gaps in Follow-up
```{r, echo=FALSE}
ggplot(tmpdat, aes(futime,subj)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Diagnosis, years") + ylab("Subject") +
geom_segment(data=tmpdat[tmpdat$pchtype3=='X',],
aes(x=time4,y=subj,xend=time6,yend=subj), color="white", size=1)
```
## Gaps in Follow-up
* After an event, subjects are not at risk during the course of antibiotics or for 6 days after treatment ends (`rhDNase` data)
* Subjects move out of the region temporarily and are not "at risk" during that time
## Analysis by Time Period
```{r, echo=FALSE}
annot <- data.frame(x=c(4,9,15), y=20, text=c('A','B','C'))
ggplot(tmpdat, aes(futime,subj, color=treated)) +
geom_segment(data=tmpdat,aes(x=0,y=subj,xend=futime,yend=subj),size=1) + plotTheme +
geom_point(data=tmpdat, aes(x=futime, y=subj, shape=Endpoint),size=4) +
scale_shape_manual(values=c("O","X")) + xlab("Time since Diagnosis, years") + ylab("Subject") + geom_vline(xintercept=c(5,10)) +
geom_text(data=annot, aes(x,y, label=text), color='purple', size=6)
```
## Analysis by Time Period
* Risk of event during first 5 years after cancer is different than afterwards
* Effect decreases over time
+ baseline lab variable
+ treatment
## Simple Example: Data we have
* Initial dataset has 1 observation per subject
* Surgery is a time-dependent covariate
```{r}
## create dataset with 3 subjects
## d1 includes baseline data to be retained in the analysis dataset
d1 <- data.frame(id=1:3,age=c(40,20,50))
## d2 includes data with event and TD covariate information
d2 <- data.frame(id=1:3, tm_fu=c(10, 20, 30), event=c(0,1,1), tm_surg=c(5,8,NA))
kable(merge(d1, d2, by='id')[,c('id','age','tm_fu','event','tm_surg')], row.names=F)
```
## Simple Example: What we want
```{r}
tmp <- tmerge(data1=d1, data2=d2, id=id,
death=event(tm_fu, event),
surgery=tdc(tm_surg))
kable(tmp[,c('id','tstart','tstop','death','age','surgery')], row.names=F)
```
## Counting Process data
* (time1, time2] time interval
* status at the end of time2
* covariates as of time1
##
### \textcolor{blue}{Creating Start/Stop Data}
## The `tmerge` function
* `tmerge` function in `survival` package: tool for creating start/stop data
* Sequential insertion
+ Build the dataset one covariate or endpoint at a time
+ Each addition will be "slipped in" to the original data in the same way that one
would slide a new card into an existing deck of cards
## The `tmerge` function
* The basic form of the function call is
```{r, eval=FALSE, echo=TRUE}
newdata <- tmerge(data1, data2, id,
newvar=tdc(time, value), ...)
```
* primary arguments:
+ data1: baseline data to be retained in the analysis dataset
+ data2: source for new data including events and time-dependent covariates
+ id: subject identifier used to merge the data together
+ ...: additional arguments that add variables to the dataset
+ tstart, tstop: used to set the time range for each subject
+ options
## The `tmerge` function
* The key part of the call are the "..." arguments,
which can be one of 4 types:
+ tdc() and cumtdc() add a time-dependent covariate
+ event() and cumevent() add a new endpoint
* Resulting dataset has 3 new variables (at least):
+ `id`: identifier indicating which rows belong to the same subject
+ `tstart`: start of the interval
+ `tstop`: end of the interval
## Example
- Baseline data: d1
```{r}
d1
```
- Time varying data: d2
```{r}
d2
```
## Example: step 1 - create start/stop time
```{r, echo=TRUE}
step1 <- tmerge(data1=d1, data2=d2, id=id,
death=event(tm_fu, event))
step1
```
## Example: step 2 - create time-dependent covariate
```{r, echo=TRUE}
step2 <- tmerge(data1=step1, data2=d2, id=id,
surgery=tdc(tm_surg))
step2
```
##
This can also be done in just one step:
```{r, echo=TRUE, eval=FALSE}
tmerge(data1=d1, data2=d2, id=id,
death=event(tm_fu, event),
surgery=tdc(tm_surg))
```
## `tcount` attribute
```{r, echo=TRUE, eval=FALSE}
attr(step2, "tcount")
```
```{r}
tmp <- attr(step2, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
## `tcount` attribute
`tcount` - a tool to check data
* Time outside the specified time frame.
+ "early" occur before the first interval for a subject
+ "late" occur after the last interval for a subject
+ "gap" times fall into a gap
+ These events will be discarded.
+ A TD covariate value will be applied to later intervals
* "within" fall inside an existing interval and cause it to be split into two
## `tcount` attribute
* Observations that fall exactly on the edge of an interval but within the (min, max] time for a subject are counted as being on a "leading" edge, "trailing" edge or "boundary".
* "tied" shows # of additions where the id and time point were identical.
## `tcount` attribute
```{r}
plot(c(0, 75), c(0,2), xlab="Time", ylab="", yaxt='n', type='n')
segments(c(10, 26, 34), c(1,1,1), c(18, 31, 65), c(1,1,1), lwd=2)
arrows(c(5, 15, 21, 26, 31, 70), rep(c(1.4, .6), 3), c(5, 15, 21, 26, 31, 70),
rep(c(1.05, .95), 3), angle=20, length=.1)
text(c(5, 15, 21, 26, 31, 70), rep(c(1.5, .5), 3),
c("early", "within", "gap", "leading", "trailing", "late"))
```
## `tcount` attribute
* 3 *trailing* deaths
* 2 *within* splits with surgery
```{r}
step2
```
## Example: Original Analysis, Stanford heart transplant data
* Original analysis used: futime, fustat, transplant status, and age
+ Transplant happened after baseline
+ `jasa` dataset
```{r}
naive <- coxph(Surv(futime, fustat) ~ age + transplant, data=jasa)
naive
```
**==> Immortal time bias <==**
## \textcolor{yellow}{Your Turn - Create the Correct Data}
* Stanford heart transplant data (`jasa`)
+ wait.time: time before transplant (tx)
+ futime: follow-up time
+ fustat: dead or alive
+ age
* Create
|id | tstart | tstop | death | age | tx |
|:---|:-----|:------|:-----|:----|:---------|
| 1 | . | . | . | . | .|
See the file `exercises/2.jasa.Rmd`.
## Stanford Heart Transplant
```{r eval=FALSE, echo=TRUE}
jasa$id <- 1:nrow(jasa)
sdata <- tmerge(jasa, jasa, id=id,
death = event(futime, fustat),
tx = tdc(wait.time))
```

## What went wrong?
```{r}
jasa$id <- 1:nrow(jasa)
```
```{r, echo=TRUE}
jasa %>% filter(futime==0) %>%
select(id, futime, fustat, wait.time)
```
* **1 subject died on the day of entry.** (0,0) is an illegal
time interval for `coxph`.
It suffices to have them die on day 0.5.
```{r, echo=TRUE}
jasa$futime <- pmax(0.5, jasa$futime)
```
## Rerun
```{r, echo=TRUE}
sdata <- tmerge(jasa, jasa, id=id,
death = event(futime, fustat),
tx = tdc(wait.time))
```
```{r, echo=TRUE, eval=FALSE}
attr(sdata, "tcount")
```
```{r}
tmp <- attr(sdata, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
## What does "trailing" mean?
```{r, echo=TRUE}
jasa %>% filter(wait.time==futime) %>%
select(id, futime, fustat, wait.time)
```
* **Subject died on the same day as their procedure.**
The problem is resolved by
moving the transplant back 0.5 day.
```{r, echo=TRUE}
jasa$wait.time <- if_else(jasa$wait.time==jasa$futime,
jasa$wait.time - .5,
jasa$wait.time)
```
## Rerun again
```{r, echo=TRUE}
sdata <- tmerge(jasa, jasa, id=id,
death = event(futime, fustat),
tx = tdc(wait.time))
```
```{r, echo=TRUE, eval=FALSE}
attr(sdata, "tcount")
```
```{r}
tmp <- attr(sdata, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
\textcolor{purple}{Yay!}
## Cox Model
```{r, echo=TRUE}
fit <- coxph(Surv(tstart, tstop, death) ~ age + tx,
data=sdata)
fit
```
## Example: Continuous values that change over time
* `pbcseq` is from the Mayo Clinic trial in primary biliary cirrhosis (PBC) of the liver conducted between 1974 and 1984. `r length(unique(pbcseq$id))` subjects were randomized to placebo or D-penicillamine.
* The data has `r nrow(pbcseq)` observations with repeated laboratory values + baseline variables
```{r}
pbcseq %>% filter(id %in% c(1,5) ) %>%
select(id,futime,status,trt,day, alk.phos, bili) %>%
kable()
```
## Create baseline data
```{r, echo=TRUE}
# baseline
pbc_b <- pbcseq %>% select(id:sex) %>% distinct()
head(pbc_b)
```
## Look at status
```{r, echo=TRUE}
table(pbc_b$status)
```
After discussion with investigator, decided that in this instance, transplant (1) and death (2) can both be treated as death.
```{r, echo=TRUE}
pbc_b$status2 <- as.numeric(pbc_b$status>0)
```
## Set range
```{r, echo=TRUE}
# set range
newpbc <- tmerge(pbc_b, pbc_b, id=id,
death = event(futime, status2))
print(head(newpbc),digits=2)
```
## Create new TDC variables
```{r, echo=TRUE}
newpbc <- tmerge(newpbc, pbcseq, id = id,
ascites = tdc(day, ascites),
bili = tdc(day, bili),
albumin = tdc(day, albumin))
```
##
```{r, echo=FALSE}
newpbc %>% select(id, tstart, tstop, death, sex, ascites, bili, albumin) %>%
head() %>% kable()
```
## Example: Continuous values that change over time
```{r, echo=TRUE, eval=FALSE}
attr(newpbc, "tcount")
```
```{r}
tmp <- attr(newpbc, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
## Example: Continuous values that change over time
* Missing values in time or value from `data2` are ignored
+ Consequence: "last value carried forward"
* Default can be changed by adding `options=list(na.rm=FALSE)` to the second call
+ Any `tdc` calls with a missing time are still ignored, independent
of the na.rm value, since we would not know where to insert them.
##
Code available in `3.pbc.Rmd`
## How covariates differ from events
* Time-dependent covariates
+ Apply from the *start* of a new interval
+ Persist for all remaining intervals unless subsequently changed
* Events
+ Occur at the *end* of an interval
+ Only occur once
## \textcolor{yellow}{Your Turn}
* Chronic Granulotamous Disease (`cgd0`)
+ id, treat, sex, age
+ futime: follow-up time
+ etime1-etime7: up to 7 infection times/subject
* Create
|id | tstart | tstop | infect | treat | enum |
|:--|:-------|:------|:-------|:------|:-----|
| 1 | . | . | . | . | . |
where `enum` is the interval number/id
See `exercises/4.cgd.Rmd`
## CGD
```{r, echo=TRUE}
newcgd <- tmerge(data1=cgd0, data2=cgd0,
id=id, tstop=futime,
infect=event(etime1), infect=event(etime2),
infect=event(etime3), infect=event(etime4),
infect=event(etime5), infect=event(etime6),
infect=event(etime7))
newcgd <- tmerge(newcgd, newcgd, id=id,
enum=cumtdc(tstart))
```
## CGD
```{r, echo=TRUE, eval=FALSE}
attr(newcgd, "tcount")
```
```{r}
tmp <- attr(newcgd, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
## CGD
```{r, echo=TRUE}
newcgd %>% filter(id==2) %>%
select(id, tstart, tstop, infect, enum)
```
## CGD
```{r, echo=TRUE}
fit <- coxph(Surv(tstart,tstop,infect) ~ treat +
steroids + inherit, id=id, data=newcgd)
fit
```
## CGD
* Look at the first infection versus all infections
```{r, echo=TRUE}
fit0 <- coxph(Surv(tstart,tstop,infect) ~ treat + steroids +
inherit, id=id, data=newcgd, subset=enum==1)
round(cbind(first=coef(fit0),all=coef(fit)), 3)
```
## Gaps
* *Time dependent covariates* that occur before the start of a subject's
follow-up interval or during a gap in time do not generate a new interval split, but they do set the value of that covariate for future times.
+ During a subject's time under observation we would
like the variable "Has diabetes"
to be accurate
* *Events* that occur in a gap are not counted.
+ Don't know the appropriate comparison group, so we ignore those events.
```{r, echo=FALSE, eval=TRUE,fig.height=2,fig.width=6}
par(mar=c(4,0,0,0),lwd=2)
plot(c(0,10),c(0,5),type='n',axes=F,xlab='Time since study entry, years',ylab='')
axis(1,at=0:10,label=0:10)
lines(x=c(0,2.1),y=c(1.5, 1.5),col='black')
lines(x=c(3.6,7.1),y=c(1.5, 1.5),col='red', lty=2)
text('C',x=3,y=1.6)
text('O',x=7.1,y=1.6)
lines(c(0,2.4),c(0.5, 0.5),col='black')
lines(c(3.5,4.6),c(0.5, 0.5),col='black')
lines(c(5.5,8.1),c(0.5, 0.5),col='black')
text(x=8.1, y=.6, 'E')
text(x=5, y=.6, 'E', font=3, col='green')
text(x=2, y=.6, 'E')
text(9.5,1.6,'TDC')
text(9.5,.6,'Event')
```
## Example: Intentional gaps, rhDNase
* Randomized clinical trial examining a treatment for cystic fibrosis
* Infection is the event of interest, indicated by `ivstart`
* For 6 days after `ivstop`, the subject is not at risk for a new infection
```{r}
knitr::asis_output("\\footnotesize")
# 2 subjects
print(rhDNase[rhDNase$id%in%c(1,129),], row.names=F)
```
## \textcolor{yellow}{Your Turn}
Use the `rhDNase` data found in the `survival` package:
1. Create range for when subjects are under observation (`tmerge`)
2. Create event for each infection (`tmerge`)
3. Create intervals where they are not at risk (`tmerge`)
4. Remove intervals where not at risk
5. Add a counter for each person (`tmerge`)
6. Check data and `tcount` attribute
See `exercises/5.dnase.Rmd`
## rhDNase
Quick look at the data
```{r, echo=TRUE}
dim(rhDNase)
head(rhDNase)
```
## rhDNase
```{r, echo=TRUE}
table(table(rhDNase$id)) # number obs/id
table(!is.na(rhDNase$ivstart)) # number events
```
## rhDNase
Create range for when subjects are under observation
```{r echo=TRUE}
# Make sure data is sorted by id, ivstart time
dnase <- rhDNase %>% arrange(id,ivstart) %>%
mutate(end.tm = as.numeric(end.dt - entry.dt))
# 1st obs/id
dnase.b <- dnase %>% distinct(id, .keep_all=TRUE)
dn1 <- tmerge(dnase.b[,c('id','inst','trt','fev')],
dnase.b, tstop=end.tm, id=id)
```
## rhDNase
Create event for each infection
```{r echo=TRUE}
dn2 <- tmerge(dn1, dnase,
infect=event(ivstart), id=id)
dn2[dn2$id==129,]
```
## rhDNase
Create intervals where they are not at risk
```{r, echo=TRUE}
dn3 <- tmerge(dn2, dnase,
no.risk=event(ivstop+6), id=id)
dn3[dn3$id==129,]
```
## rhDNase
Remove intervals where not at risk
```{r, echo=TRUE}
dn4 <- dn3[dn3$no.risk!=1,]
```
Add a counter for each person
```{r, echo=TRUE}
newdnase <- tmerge(dn4, dn4, enum=cumtdc(tstart), id=id)
```
## rhDNase
Check to make sure code worked correct
```{r echo=TRUE}
newdnase[newdnase$id==129,]
```
## rhDNase: check `tcount`
```{r, echo=TRUE, eval=FALSE}
attr(newdnase, "tcount")
```
```{r, echo=FALSE}
tmp <- attr(newdnase, "tcount")
colnames(tmp)[6] <- "lead"
colnames(tmp)[7] <- "trail"
tmp
```
## `tmerge` summary