-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathsurvival_analysis_in_r_tutorial.html
5342 lines (4814 loc) · 148 KB
/
survival_analysis_in_r_tutorial.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Survival Analysis in R</title>
<script src="site_libs/header-attrs-2.21/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<link href="site_libs/bootstrap-5.2.2/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-5.2.2/bootstrap.bundle.min.js"></script>
<script src="site_libs/bs3compat-0.4.2/transition.js"></script>
<script src="site_libs/bs3compat-0.4.2/tabs.js"></script>
<script src="site_libs/bs3compat-0.4.2/bs3compat.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-6.4.0/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.4.0/css/v4-shims.min.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Emily C. Zabor</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="http://www.emilyzabor.me">
<span class="fa fa-home fa-lg"></span>
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://scholar.google.com/citations?user=tLbQTZMAAAAJ&hl=en">
<span class="ai ai-google-scholar ai-lg"></span>
</a>
</li>
<li>
<a href="http://www.emilyzabor.me/files/Zabor_Emily_CV.pdf">
<span class="ai ai-cv ai-lg"></span>
</a>
</li>
<li>
<a href="http://github.com/zabore/tutorials">
<span class="fab fa-github fa-lg"></span>
</a>
</li>
<li>
<a href="https://twitter.com/zabormetrics">
<span class="fab fa-twitter fa-lg"></span>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/emily-zabor-59b902b7/">
<span class="fab fa-linkedin fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Survival Analysis in R</h1>
</div>
<p><link rel="stylesheet" href="academicicons/css/academicons.min.css"/></p>
<p>This tutorial provides an introduction to survival analysis, and to
conducting a survival analysis in R. This tutorial was originally
presented at the Memorial Sloan Kettering Cancer Center R-Presenters
series on August 30, 2018. It was then modified for a more extensive
training at Memorial Sloan Kettering Cancer Center in March, 2019.
Updates, sometimes significant, are made when new functionality becomes
available in R. This tutorial reflects my own opinions about the best
functionality available in R for survival analysis.</p>
<p><strong>Last updated: 2023-06-21</strong></p>
<p>First, install and load some packages that will be used
throughout.</p>
<pre class="r"><code># Install packages if needed
# install.packages(c("knitr", "dplyr", "survival", "ggplot2", "here", "tibble"))
library(knitr)
library(dplyr)
library(survival)
library(ggplot2)
library(tibble)
# devtools::install_github("zabore/ezfun")
ezfun::set_ccf_palette("contrast")</code></pre>
<div id="part-1-introduction-to-survival-analysis"
class="section level1">
<h1>Part 1: Introduction to Survival Analysis</h1>
<p>This presentation will cover some basics of survival analysis, and
the following series of tutorial papers can be helpful for additional
reading:</p>
<blockquote>
<p>Clark, T., Bradburn, M., Love, S., & Altman, D. (2003). Survival
analysis part I: Basic concepts and first analyses. 232-238. ISSN
0007-0920.</p>
</blockquote>
<blockquote>
<p>M J Bradburn, T G Clark, S B Love, & D G Altman. (2003). Survival
Analysis Part II: Multivariate data analysis – an introduction to
concepts and methods. British Journal of Cancer, 89(3), 431-436.</p>
</blockquote>
<blockquote>
<p>Bradburn, M., Clark, T., Love, S., & Altman, D. (2003). Survival
analysis Part III: Multivariate data analysis – choosing a model and
assessing its adequacy and fit. 89(4), 605-11.</p>
</blockquote>
<blockquote>
<p>Clark, T., Bradburn, M., Love, S., & Altman, D. (2003). Survival
analysis part IV: Further concepts and methods in survival analysis.
781-786. ISSN 0007-0920.</p>
</blockquote>
<div id="the-basics" class="section level2">
<h2>The basics</h2>
<p>Survival data are time-to-event data that consist of a distinct start
time and end time.</p>
<p>Examples from cancer:</p>
<ul>
<li>Time from surgery to death</li>
<li>Time from start of treatment to progression</li>
<li>Time from response to recurrence</li>
</ul>
<p>Time-to-event data are common in many other fields. Some other
examples include:</p>
<ul>
<li>Time from HIV infection to development of AIDS</li>
<li>Time to heart attack</li>
<li>Time to onset of substance abuse</li>
<li>Time to initiation of sexual activity</li>
<li>Time to machine malfunction</li>
</ul>
<p>Because time-to-event data are common in many fields, it also goes by
names besides survival analysis including:</p>
<ul>
<li>Reliability analysis</li>
<li>Duration analysis</li>
<li>Event history analysis</li>
<li>Time-to-event analysis</li>
</ul>
<p>A key feature of survival data is <strong>censoring</strong>.</p>
<p><img src="img/trial_anatomy.png" /><!-- --></p>
<blockquote>
<p>RICH JT, NEELY JG, PANIELLO RC, VOELKER CCJ, NUSSENBAUM B, WANG EW. A
PRACTICAL GUIDE TO UNDERSTANDING KAPLAN-MEIER CURVES. Otolaryngology
head and neck surgery: official journal of American Academy of
Otolaryngology Head and Neck Surgery. 2010;143(3):331-336. <a
href="doi:10.1016/j.otohns.2010.05.007"
class="uri">doi:10.1016/j.otohns.2010.05.007</a>.</p>
</blockquote>
<p>A subject may be censored due to:</p>
<ul>
<li>Loss to follow-up</li>
<li>Withdrawal from study</li>
<li>No event by end of fixed study period</li>
</ul>
<p>Specifically these are examples of <strong>right</strong> censoring.
Left censoring and interval censoring are also possible, and methods
exist to analyze these types of data, but this tutorial will be focus on
right censoring.</p>
<p>To illustrate the impact of censoring, suppose we have the following
data:</p>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/swimmer-1.png" width="480" /></p>
<p>How would we compute the proportion who are event-free at 10
years?</p>
<ul>
<li>Subjects 6 and 7 were <strong>event-free at 10 years</strong>.</li>
<li>Subjects 2, 9, and 10 had the <strong>event before 10
years</strong>.</li>
<li>Subjects 1, 3, 4, 5, and 8 were <strong>censored before 10
years</strong>, so we don’t know whether they had the event or not at 10
years. But we know something about them - that they were each followed
for a certain amount of time without the event of interest prior to
being censored.</li>
</ul>
<p><em>Survival analysis techniques provide a way to appropriately
account for censored patients in the analysis.</em></p>
<p>Other reasons specialized analysis techniques are needed:</p>
<ul>
<li>The distribution of follow-up times is skewed, and may differ
between censored patients and those with events</li>
<li>Follow-up times are always positive</li>
</ul>
<p>Example of the distribution of follow-up times according to event
status:</p>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/fuptimes-1.png" width="480" /></p>
<p>To analyze survival data, we need to know the observed time <span
class="math inline">\(Y_i\)</span> and the event indicator <span
class="math inline">\(\delta_i\)</span>. For subject <span
class="math inline">\(i\)</span>:</p>
<ul>
<li>Observed time <span class="math inline">\(Y_i = \min(T_i,
C_i)\)</span> where <span class="math inline">\(T_i\)</span> = event
time and <span class="math inline">\(C_i\)</span> = censoring time</li>
<li>Event indicator <span class="math inline">\(\delta_i\)</span> = 1 if
event observed (i.e. <span class="math inline">\(T_i \leq C_i\)</span>),
= 0 if censored (i.e. <span class="math inline">\(T_i >
C_i\)</span>)</li>
</ul>
<p>The probability that a subject will survive beyond any given
specified time</p>
<p><span class="math display">\[S(t) = Pr(T>t) = 1 -
F(t)\]</span></p>
<p><span class="math inline">\(S(t)\)</span>: survival function <span
class="math inline">\(F(t) = Pr(T \leq t)\)</span>: cumulative
distribution function</p>
<p>In theory the survival function is smooth; in practice we observe
events on a discrete time scale.</p>
<p>The <strong>survival probability</strong> at a certain time, <span
class="math inline">\(S(t)\)</span>, is a conditional probability of
surviving beyond that time, given that an individual has survived just
prior to that time. The survival probability can be estimated as the
number of patients who are alive without loss to follow-up at that time,
divided by the number of patients who were alive just prior to that
time.</p>
<p>The <strong>Kaplan-Meier</strong> estimate of survival probability at
a given time is the product of these conditional probabilities up until
that given time.</p>
<p>At time 0, the survival probability is 1, i.e. <span
class="math inline">\(S(t_0) = 1\)</span>.</p>
</div>
<div id="packages" class="section level2">
<h2>Packages</h2>
<p>In this section, we will use the following packages:</p>
<pre class="r"><code># install.packages(c("lubridate", "ggsurvfit", "gtsummary", "tidycmprsk"))
library(lubridate)
library(ggsurvfit)
library(gtsummary)
library(tidycmprsk)
# devtools::install_github("zabore/condsurv")
library(condsurv)</code></pre>
</div>
<div id="the-lung-dataset" class="section level2">
<h2>The <code>lung</code> dataset</h2>
<p>Throughout this section, we will use the <code>lung</code> dataset
from the {survival} package as example data. The data contain subjects
with advanced lung cancer from the North Central Cancer Treatment Group.
We will focus on the following variables throughout this tutorial:</p>
<ul>
<li>time: Observed survival time in days</li>
<li>status: censoring status 1=censored, 2=dead</li>
<li>sex: 1=Male, 2=Female</li>
</ul>
<p><em>Note that the status is coded in a non-standard way in this
dataset. Typically you will see 1=event, 0=censored</em>. Let’s recode
it to avoid confusion:</p>
<pre class="r"><code>lung <-
lung %>%
mutate(
status = recode(status, `1` = 0, `2` = 1)
)</code></pre>
<p>Now we have:</p>
<ul>
<li>time: Observed survival time in days</li>
<li>status: censoring status 0=censored, 1=dead</li>
<li>sex: 1=Male, 2=Female</li>
</ul>
<p>Here are the first 6 observations:</p>
<pre class="r"><code>head(lung[, c("time", "status", "sex")])</code></pre>
<pre><code>## time status sex
## 1 306 1 1
## 2 455 1 1
## 3 1010 0 1
## 4 210 1 1
## 5 883 1 1
## 6 1022 0 1</code></pre>
<p><em>Note</em>: the <code>Surv()</code> function in the {survival}
package accepts by default TRUE/FALSE, where TRUE is event and FALSE is
censored; 1/0 where 1 is event and 0 is censored; or 2/1 where 2 is
event and 1 is censored. <strong>Please take care to ensure the event
indicator is properly formatted.</strong></p>
</div>
<div id="calculating-survival-times" class="section level2">
<h2>Calculating survival times</h2>
<p>Data will often come with start and end dates rather than
pre-calculated survival times. The first step is to make sure these are
formatted as dates in R.</p>
<p>Let’s create a small example dataset with variables
<code>sx_date</code> for surgery date and <code>last_fup_date</code> for
the last follow-up date:</p>
<pre class="r"><code>date_ex <-
tibble(
sx_date = c("2007-06-22", "2004-02-13", "2010-10-27"),
last_fup_date = c("2017-04-15", "2018-07-04", "2016-10-31")
)
date_ex</code></pre>
<pre><code>## # A tibble: 3 × 2
## sx_date last_fup_date
## <chr> <chr>
## 1 2007-06-22 2017-04-15
## 2 2004-02-13 2018-07-04
## 3 2010-10-27 2016-10-31</code></pre>
<p>We see these are both character variables, but we need them to be
formatted as dates.</p>
<p>We will use the {lubridate} package to work with dates. In this case,
we need to use the <code>ymd()</code> function to change the format,
since the dates are currently in the character format where the year
comes first, followed by the month, and followed by the day.</p>
<pre class="r"><code>date_ex <-
date_ex %>%
mutate(
sx_date = ymd(sx_date),
last_fup_date = ymd(last_fup_date)
)
date_ex</code></pre>
<pre><code>## # A tibble: 3 × 2
## sx_date last_fup_date
## <date> <date>
## 1 2007-06-22 2017-04-15
## 2 2004-02-13 2018-07-04
## 3 2010-10-27 2016-10-31</code></pre>
<p>Now we see that the two dates are formatted as date rather than as
character. Access the help page with <code>?ymd</code> to see all date
format options.</p>
<p>Now that the dates are formatted, we need to calculate the difference
between start and end dates in some units, usually months or years.
Using the {lubridate} package, the operator <code>%--%</code> designates
a time interval, which is then converted to the number of elapsed
seconds using <code>as.duration()</code> and finally converted to years
by dividing by <code>dyears(1)</code>, which gives the number of seconds
in a year.</p>
<pre class="r"><code>date_ex <-
date_ex %>%
mutate(
os_yrs = as.duration(sx_date %--% last_fup_date) / dyears(1)
)
date_ex</code></pre>
<pre><code>## # A tibble: 3 × 3
## sx_date last_fup_date os_yrs
## <date> <date> <dbl>
## 1 2007-06-22 2017-04-15 9.82
## 2 2004-02-13 2018-07-04 14.4
## 3 2010-10-27 2016-10-31 6.01</code></pre>
<p>Now we have our observed time for use in survival analysis.</p>
<p><em>Note</em>: we need to load the {lubridate} package using a call
to <code>library</code> in order to be able to access the special
operators (similar to situation with pipes - i.e. we can’t use
<code>lubridate::ymd()</code> and then expect to use the special
operators).</p>
</div>
<div id="creating-survival-objects-and-curves" class="section level2">
<h2>Creating survival objects and curves</h2>
<p>The Kaplan-Meier method is the most common way to estimate survival
times and probabilities. It is a non-parametric approach that results in
a step function, where there is a step down each time an event
occurs.</p>
<p>The <code>Surv()</code> function from the {survival} package creates
a survival object for use as the response in a model formula. There will
be one entry for each subject that is the survival time, which is
followed by a <code>+</code> if the subject was censored. Let’s look at
the first 10 observations:</p>
<pre class="r"><code>Surv(lung$time, lung$status)[1:10]</code></pre>
<pre><code>## [1] 306 455 1010+ 210 883 1022+ 310 361 218 166</code></pre>
<p>We see that subject 1 had an event at time 306 days, subject 2 had an
event at time 455 days, subject 3 was censored at time 1010 days,
etc.</p>
<p>The <code>survfit()</code> function creates survival curves using the
Kaplan-Meier method based on a formula. Let’s generate the overall
survival curve for the entire cohort, assign it to object
<code>s1</code>, and look at the structure using <code>str()</code>:</p>
<pre class="r"><code>s1 <- survfit(Surv(time, status) ~ 1, data = lung)
str(s1)</code></pre>
<pre><code>## List of 16
## $ n : int 228
## $ time : num [1:186] 5 11 12 13 15 26 30 31 53 54 ...
## $ n.risk : num [1:186] 228 227 224 223 221 220 219 218 217 215 ...
## $ n.event : num [1:186] 1 3 1 2 1 1 1 1 2 1 ...
## $ n.censor : num [1:186] 0 0 0 0 0 0 0 0 0 0 ...
## $ surv : num [1:186] 0.996 0.982 0.978 0.969 0.965 ...
## $ std.err : num [1:186] 0.0044 0.00885 0.00992 0.01179 0.01263 ...
## $ cumhaz : num [1:186] 0.00439 0.0176 0.02207 0.03103 0.03556 ...
## $ std.chaz : num [1:186] 0.00439 0.0088 0.00987 0.01173 0.01257 ...
## $ type : chr "right"
## $ logse : logi TRUE
## $ conf.int : num 0.95
## $ conf.type: chr "log"
## $ lower : num [1:186] 0.987 0.966 0.959 0.947 0.941 ...
## $ upper : num [1:186] 1 1 0.997 0.992 0.989 ...
## $ call : language survfit(formula = Surv(time, status) ~ 1, data = lung)
## - attr(*, "class")= chr "survfit"</code></pre>
<p>Some key components of this <code>survfit</code> object that will be
used to create survival curves include:</p>
<ul>
<li><code>time</code>: the timepoints at which the curve has a step,
i.e. at least one event occurred</li>
<li><code>surv</code>: the estimate of survival at the corresponding
<code>time</code></li>
</ul>
</div>
<div id="kaplan-meier-plots" class="section level2">
<h2>Kaplan-Meier plots</h2>
<p>We will use the {ggsurvfit} package to generate Kaplan-Meier plots.
This package aims to ease plotting of time-to-event endpoints using the
power of the {ggplot2} package. See <a
href="http://www.danieldsjoberg.com/ggsurvfit/index.html">http://www.danieldsjoberg.com/ggsurvfit/index.html</a>
for details.</p>
<p><em>Note</em>: alternatively, survival plots can be created using
base R or the {survminer} package.</p>
<p>The {ggsurvfit} package works best if you create the
<code>survfit</code> object using the included
<code>ggsurvfit::survfit2()</code> function, which uses the same syntax
to what we saw previously with <code>survival::survfit()</code>. The
<code>ggsurvfit::survfit2()</code> tracks the environment from the
function call, which allows the plot to have better default values for
labeling and p-value reporting.</p>
<pre class="r"><code>survfit2(Surv(time, status) ~ 1, data = lung) %>%
ggsurvfit() +
labs(
x = "Days",
y = "Overall survival probability"
)</code></pre>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/unnamed-chunk-3-1.png" width="480" /></p>
<p>The default plot in <code>ggsurvfit()</code> shows the step function
only. We can add the confidence interval using
<code>add_confidence_interval()</code>:</p>
<pre class="r"><code>survfit2(Surv(time, status) ~ 1, data = lung) %>%
ggsurvfit() +
labs(
x = "Days",
y = "Overall survival probability"
) +
add_confidence_interval()</code></pre>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/unnamed-chunk-4-1.png" width="480" /></p>
<p>Typically we will also want to see the numbers at risk in a table
below the x-axis. We can add this using
<code>add_risktable()</code>:</p>
<pre class="r"><code>survfit2(Surv(time, status) ~ 1, data = lung) %>%
ggsurvfit() +
labs(
x = "Days",
y = "Overall survival probability"
) +
add_confidence_interval() +
add_risktable()</code></pre>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/unnamed-chunk-5-1.png" width="480" /></p>
<p>Plots can be customized using many standard {ggplot2} options.</p>
</div>
<div id="estimating-x-year-survival" class="section level2">
<h2>Estimating <span class="math inline">\(x\)</span>-year survival</h2>
<p>One quantity often of interest in a survival analysis is the
probability of surviving beyond a certain number of years, <span
class="math inline">\(x\)</span>.</p>
<p>For example, to estimate the probability of surviving to <span
class="math inline">\(1\)</span> year, use <code>summary</code> with the
<code>times</code> argument (<em>Note:</em> the <code>time</code>
variable in the <code>lung</code> data is actually in days, so we need
to use <code>times = 365.25</code>)</p>
<pre class="r"><code>summary(survfit(Surv(time, status) ~ 1, data = lung), times = 365.25)</code></pre>
<pre><code>## Call: survfit(formula = Surv(time, status) ~ 1, data = lung)
##
## time n.risk n.event survival std.err lower 95% CI upper 95% CI
## 365 65 121 0.409 0.0358 0.345 0.486</code></pre>
<p>We find that the <span class="math inline">\(1\)</span>-year
probability of survival in this study is 41%.</p>
<p>The associated lower and upper bounds of the 95% confidence interval
are also displayed.</p>
<p>The <span class="math inline">\(1\)</span>-year survival probability
is the point on the y-axis that corresponds to <span
class="math inline">\(1\)</span> year on the x-axis for the survival
curve.</p>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/unnamed-chunk-6-1.png" width="480" /></p>
<p>What happens if you use a “naive” estimate? Here “naive” means that
the patients who were censored prior to 1-year are considered event-free
and included in the denominator.</p>
<p>121 of the 228 patients in the <code>lung</code> data died by <span
class="math inline">\(1\)</span> year so the “naive” estimate is
calculated as:</p>
<p><span class="math display">\[\Big(1 - \frac{121}{228}\Big) \times 100
= 47\%\]</span> You get an <strong>incorrect</strong> estimate of the
<span class="math inline">\(1\)</span>-year probability of survival when
you ignore the fact that 42 patients were censored before <span
class="math inline">\(1\)</span> year.</p>
<p>Recall the <strong>correct</strong> estimate of the <span
class="math inline">\(1\)</span>-year probability of survival,
accounting for censoring using the Kaplan-Meier method, was 41%.</p>
<p>Ignoring censoring leads to an <strong>overestimate</strong> of the
overall survival probability. Imagine two studies, each with 228
subjects. There are 165 deaths in each study. Censoring is ignored in
one (blue line), censoring is accounted for in the other (yellow line).
The censored subjects only contribute information for a portion of the
follow-up time, and then fall out of the risk set, thus pulling down the
cumulative probability of survival. Ignoring censoring erroneously
treats patients who are censored as part of the risk set for the entire
follow-up period.</p>
<p><img src="survival_analysis_in_r_tutorial_files/figure-html/unnamed-chunk-7-1.png" width="480" /></p>
<p>We can produce nice tables of <span
class="math inline">\(x\)</span>-time survival probability estimates
using the <code>tbl_survfit()</code> function from the {gtsummary}
package:</p>
<pre class="r"><code>survfit(Surv(time, status) ~ 1, data = lung) %>%
tbl_survfit(
times = 365.25,
label_header = "**1-year survival (95% CI)**"
)</code></pre>
<div id="thodvqsjjd" style="padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;">
<style>#thodvqsjjd table {
font-family: system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#thodvqsjjd thead, #thodvqsjjd tbody, #thodvqsjjd tfoot, #thodvqsjjd tr, #thodvqsjjd td, #thodvqsjjd th {
border-style: none;
}
#thodvqsjjd p {
margin: 0;
padding: 0;
}
#thodvqsjjd .gt_table {
display: table;
border-collapse: collapse;
line-height: normal;
margin-left: auto;
margin-right: auto;
color: #333333;
font-size: 16px;
font-weight: normal;
font-style: normal;
background-color: #FFFFFF;
width: auto;
border-top-style: solid;
border-top-width: 2px;
border-top-color: #A8A8A8;
border-right-style: none;
border-right-width: 2px;
border-right-color: #D3D3D3;
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #A8A8A8;
border-left-style: none;
border-left-width: 2px;
border-left-color: #D3D3D3;
}
#thodvqsjjd .gt_caption {
padding-top: 4px;
padding-bottom: 4px;
}
#thodvqsjjd .gt_title {
color: #333333;
font-size: 125%;
font-weight: initial;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 5px;
padding-right: 5px;
border-bottom-color: #FFFFFF;
border-bottom-width: 0;
}
#thodvqsjjd .gt_subtitle {
color: #333333;
font-size: 85%;
font-weight: initial;
padding-top: 3px;
padding-bottom: 5px;
padding-left: 5px;
padding-right: 5px;
border-top-color: #FFFFFF;
border-top-width: 0;
}
#thodvqsjjd .gt_heading {
background-color: #FFFFFF;
text-align: center;
border-bottom-color: #FFFFFF;
border-left-style: none;
border-left-width: 1px;
border-left-color: #D3D3D3;
border-right-style: none;
border-right-width: 1px;
border-right-color: #D3D3D3;
}
#thodvqsjjd .gt_bottom_border {
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #D3D3D3;
}
#thodvqsjjd .gt_col_headings {
border-top-style: solid;
border-top-width: 2px;
border-top-color: #D3D3D3;
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #D3D3D3;
border-left-style: none;
border-left-width: 1px;
border-left-color: #D3D3D3;
border-right-style: none;
border-right-width: 1px;
border-right-color: #D3D3D3;
}
#thodvqsjjd .gt_col_heading {
color: #333333;
background-color: #FFFFFF;
font-size: 100%;
font-weight: normal;
text-transform: inherit;
border-left-style: none;
border-left-width: 1px;
border-left-color: #D3D3D3;
border-right-style: none;
border-right-width: 1px;
border-right-color: #D3D3D3;
vertical-align: bottom;
padding-top: 5px;
padding-bottom: 6px;
padding-left: 5px;
padding-right: 5px;
overflow-x: hidden;
}
#thodvqsjjd .gt_column_spanner_outer {
color: #333333;
background-color: #FFFFFF;
font-size: 100%;
font-weight: normal;
text-transform: inherit;
padding-top: 0;
padding-bottom: 0;
padding-left: 4px;
padding-right: 4px;
}
#thodvqsjjd .gt_column_spanner_outer:first-child {
padding-left: 0;
}
#thodvqsjjd .gt_column_spanner_outer:last-child {
padding-right: 0;
}
#thodvqsjjd .gt_column_spanner {
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #D3D3D3;
vertical-align: bottom;
padding-top: 5px;
padding-bottom: 5px;
overflow-x: hidden;
display: inline-block;
width: 100%;
}
#thodvqsjjd .gt_spanner_row {
border-bottom-style: hidden;
}
#thodvqsjjd .gt_group_heading {
padding-top: 8px;
padding-bottom: 8px;
padding-left: 5px;
padding-right: 5px;
color: #333333;
background-color: #FFFFFF;
font-size: 100%;
font-weight: initial;
text-transform: inherit;
border-top-style: solid;
border-top-width: 2px;
border-top-color: #D3D3D3;
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #D3D3D3;
border-left-style: none;
border-left-width: 1px;
border-left-color: #D3D3D3;
border-right-style: none;
border-right-width: 1px;
border-right-color: #D3D3D3;
vertical-align: middle;
text-align: left;
}
#thodvqsjjd .gt_empty_group_heading {
padding: 0.5px;
color: #333333;
background-color: #FFFFFF;
font-size: 100%;
font-weight: initial;
border-top-style: solid;
border-top-width: 2px;
border-top-color: #D3D3D3;
border-bottom-style: solid;
border-bottom-width: 2px;
border-bottom-color: #D3D3D3;
vertical-align: middle;
}