-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurvival_analysis.R
More file actions
305 lines (250 loc) · 9.54 KB
/
Copy pathsurvival_analysis.R
File metadata and controls
305 lines (250 loc) · 9.54 KB
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
# =============================================================================
# Survival Analysis: Kaplan-Meier and Cox Regression
#
# Author: Nikhil Kirtipal
#
# Demonstrates:
# - Kaplan-Meier estimation and log-rank test
# - Cox proportional hazards regression
# - PH assumption testing (Schoenfeld residuals)
# - Publication-ready summary tables
#
# Data: survival::lung (NCCTG Lung Cancer, 228 patients) - built into the package
# Loprinzi et al. (1994), J Clin Oncol 12:601-607
#
# Tested: R 4.4.2, survival 3.6-6, survminer 0.5.2, gtsummary 2.5.1,
# gt 1.3.0, dplyr 1.2.0, tidyr 1.3.2
#
# Replace the data preparation section to use your own clinical dataset.
# =============================================================================
library(survival)
library(survminer)
library(gtsummary)
library(gt)
library(dplyr)
library(tidyr)
#
suppressWarnings(data("lung", package = "survival"))
# ---- 0. Data preparation ----------------------------------------------------
# lung codes status as 1 = censored, 2 = dead. Survival functions expect
# 0 = censored, 1 = event, so subtract 1.
#
# ph.ecog has a single patient at level 3, which gives an unstable univariable
# model, so it is dropped. Complete cases are used throughout so that the
# unadjusted and adjusted models are fitted on the same rows.
dat <- lung %>%
filter(!is.na(ph.ecog), ph.ecog < 3) %>%
mutate(
status = status - 1,
sex = factor(sex, levels = 1:2, labels = c("Male", "Female")),
ph.ecog = factor(ph.ecog, levels = 0:2,
labels = c("Asymptomatic", "Ambulatory", "In bed <50%"))
) %>%
drop_na(time, status, sex, age, ph.ecog, wt.loss)
cat("n =", nrow(dat), " events =", sum(dat$status), "\n")
# Variable labels feed straight through to the gtsummary tables
dat <- dat %>%
labelled::set_variable_labels(
time = "Follow-up time (days)",
age = "Age (years)",
sex = "Sex",
ph.ecog = "ECOG performance status",
ph.karno = "Karnofsky score (physician)",
wt.loss = "Weight loss (lbs, 6 months)"
)
# ---- 1. Kaplan-Meier --------------------------------------------------------
surv_obj <- Surv(time = dat$time, event = dat$status)
fit <- survfit(surv_obj ~ sex, data = dat)
print(fit)
print(surv_median(fit))
pal <- c("#1B6B70", "#E07A5F") # teal, coral
km_plot <- ggsurvplot(
fit,
data = dat,
palette = pal,
pval = TRUE,
pval.size = 4.5,
pval.coord = c(20, 0.08),
conf.int = TRUE,
conf.int.alpha = 0.15,
censor.shape = "|",
censor.size = 3,
size = 1.1,
xlab = "Time (days)",
ylab = "Survival probability",
legend.title = "",
legend.labs = c("Male", "Female"),
legend = c(0.85, 0.85),
risk.table = TRUE,
risk.table.height = 0.24,
risk.table.title = "Number at risk",
risk.table.y.text = TRUE,
risk.table.y.text.col = TRUE,
risk.table.fontsize = 3.8,
tables.theme = theme_cleantable(),
break.time.by = 250,
xlim = c(0, 1000),
ggtheme = theme_minimal(base_size = 13) +
theme(
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey92", linewidth = 0.4),
axis.line = element_line(colour = "grey30", linewidth = 0.4),
axis.ticks = element_line(colour = "grey30", linewidth = 0.4),
legend.text = element_text(size = 11),
plot.margin = margin(10, 14, 6, 10)
)
)
print(km_plot)
# ---- 2. Baseline characteristics --------------------------------------------
tab1 <- dat %>%
select(age, sex, ph.ecog, wt.loss) %>%
tbl_summary(
by = sex,
missing = "no",
statistic = list(
all_categorical() ~ "{n} ({p}%)",
all_continuous() ~ "{mean} ± {sd}"
),
digits = list(
all_categorical() ~ c(0, 1),
all_continuous() ~ c(1, 1)
)
) %>%
bold_labels() %>%
add_overall(last = TRUE) %>%
add_p(pvalue_fun = ~style_pvalue(.x, digits = 3))
print(tab1)
# ---- 3. Cox proportional hazards --------------------------------------------
cox <- coxph(Surv(time, status) ~ sex + age + ph.ecog + wt.loss, data = dat)
summary(cox)
# ---- 4. Check the proportional hazards assumption ---------------------------
# The Cox model assumes hazard ratios stay constant over time. This is the
# assumption the entire model rests on, and it is routinely skipped.
#
# cox.zph tests the correlation between scaled Schoenfeld residuals and time.
# p < 0.05 means the assumption is violated for that term.
#
# If violated: stratify on the offending variable, add a time-varying
# coefficient, or move to an accelerated failure time (AFT) model.
zph <- cox.zph(cox)
print(zph)
par(mfrow = c(2, 2))
plot(zph)
par(mfrow = c(1, 1))
# Stratified alternative, if sex were to violate PH:
# cox_strat <- coxph(Surv(time, status) ~ strata(sex) + age + ph.ecog + wt.loss,
# data = dat)
# ---- 5. Unadjusted hazard ratios --------------------------------------------
hr_uni <- dat %>%
select(time, status, sex, age, ph.ecog, wt.loss) %>%
tbl_uvregression(
method = coxph,
y = Surv(time, status),
exponentiate = TRUE,
pvalue_fun = ~style_pvalue(.x, digits = 3)
) %>%
modify_column_merge(
pattern = "{estimate} ({conf.low}, {conf.high})",
rows = !is.na(estimate)
) %>%
modify_header(estimate ~ "**HR (95% CI)**") %>%
bold_labels()
print(hr_uni)
# ---- 6. Adjusted hazard ratios ----------------------------------------------
hr_multi <- cox %>%
tbl_regression(
exponentiate = TRUE,
pvalue_fun = ~style_pvalue(.x, digits = 3)
) %>%
modify_column_merge(
pattern = "{estimate} ({conf.low}, {conf.high})",
rows = !is.na(estimate)
) %>%
modify_header(estimate ~ "**HR (95% CI)**") %>%
bold_labels()
print(hr_multi)
# ---- 7. Side-by-side table --------------------------------------------------
hr_table <- tbl_merge(
tbls = list(hr_uni, hr_multi),
tab_spanner = c("**Unadjusted**", "**Adjusted**")
)
print(hr_table)
# ---- 8. Export --------------------------------------------------------------
# ggsave() does not work on a ggsurvplot object (it is a list, not a ggplot),
# so the plot is written through a png device instead.
dir.create("output", showWarnings = FALSE)
tab1_styled <- tab1 %>%
as_gt() %>%
tab_header(title = md("**Baseline characteristics**"),
subtitle = md("NCCTG Lung Cancer cohort, *n* = 212")) %>%
tab_options(
table.font.size = px(13),
column_labels.font.weight = "bold",
column_labels.border.top.width = px(2),
column_labels.border.top.color = "#1B6B70",
column_labels.border.bottom.width = px(1.5),
column_labels.border.bottom.color = "#1B6B70",
table_body.hlines.color = "grey92",
table.border.bottom.color = "#1B6B70",
table.border.bottom.width = px(2),
data_row.padding = px(5)
) %>%
tab_style(style = cell_text(color = "#1B6B70", weight = "bold"),
locations = cells_column_labels())
hr_styled <- hr_table %>%
as_gt() %>%
tab_header(title = md("**Hazard ratios for overall survival**"),
subtitle = md("Cox proportional hazards, *n* = 212, 150 events")) %>%
tab_options(
table.font.size = px(13),
column_labels.font.weight = "bold",
column_labels.border.top.width = px(2),
column_labels.border.top.color = "#1B6B70",
column_labels.border.bottom.width = px(1.5),
column_labels.border.bottom.color = "#1B6B70",
table_body.hlines.color = "grey92",
table.border.bottom.color = "#1B6B70",
table.border.bottom.width = px(2),
data_row.padding = px(5)
) %>%
tab_style(style = cell_text(color = "#1B6B70", weight = "bold"),
locations = cells_column_labels())
gtsave(tab1_styled, "output/baseline_table.docx")
gtsave(hr_styled, "output/hazard_ratios.docx")
png("output/km_curve.png", width = 2400, height = 2100, res = 300)
print(km_plot)
dev.off()
# Save the PH test as a table
zph_tab <- as.data.frame(zph$table) %>%
tibble::rownames_to_column("Term") %>%
mutate(across(c(chisq, p), ~round(.x, 3)))
write.csv(zph_tab, "output/ph_assumption_test.csv", row.names = FALSE)
print(zph_tab)
# Save the Schoenfeld residual plots
png("output/ph_diagnostics.png", width = 2400, height = 1800, res = 300)
par(mfrow = c(2, 2), mar = c(4.5, 4.5, 3, 1), bg = "white")
plot(zph[1], col = "#1B6B70", lwd = 2, main = "Sex")
abline(h = 0, col = "grey60", lty = 3)
plot(zph[2], col = "#1B6B70", lwd = 2, main = "Age")
abline(h = 0, col = "grey60", lty = 3)
plot(zph[3], col = "#1B6B70", lwd = 2, main = "ECOG performance status")
abline(h = 0, col = "grey60", lty = 3)
plot(zph[4], col = "#1B6B70", lwd = 2, main = "Weight loss")
abline(h = 0, col = "grey60", lty = 3)
par(mfrow = c(1, 1))
dev.off()
# =============================================================================
# Notes
#
# Events per variable: aim for at least 10 events per model term. This example
# has 150 events and 5 terms, which is comfortable. Fitting 9 covariates to
# 50 events is not.
#
# Missing data: coxph drops rows with NA silently. Handled up front here so
# every model uses the same sample. Otherwise the unadjusted and adjusted
# estimates come from different n and are not comparable.
#
# Multiple testing: p-values here are unadjusted. Correct them if screening
# many covariates.
# =============================================================================