-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsurvival_curves.R
72 lines (58 loc) · 2.35 KB
/
survival_curves.R
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
#######################################################################################
# Fitting a Kaplan-Meier and a
# Cox proportional hazards model.
#
# survival curves and estimate parameters for a Cox proportional hazards model
#
# adapted from
# https://stat.ethz.ch/R-manual/R-devel/library/survival/html/survfit.formula.html
#
#######################################################################################
########################################
# Load library
########################################
library(survival)
# aml has data like
# > aml
# time status x
# 1 9 1 Maintained
# 2 13 1 Maintained
# 3 13 0 Maintained
########################################
# Fit a Kaplan-Meier and plot it
########################################
fit <- survfit(Surv(time, status) ~ x, data = aml)
plot(fit, lty = 2:3)
legend(100, .8, c("Maintained", "Nonmaintained"), lty = 2:3)
################################################################################
# Fit a Cox proportional hazards model and plot the
# predicted survival for a 60 year old
################################################################################
fit <- coxph(Surv(futime, fustat) ~ age, data = ovarian)
plot(survfit(fit, newdata=data.frame(age=60)),
xscale=365.25, xlab = "Years", ylab="Survival")
###########################################
# Better plots for tiem to event analysis
###########################################
# from
# https://rpkgs.datanovia.com/survminer/index.html
# install.packages("survminer")
library("survminer")
fit <- survfit(Surv(time, status) ~ sex, data = lung)
ggsurvplot(fit, data = lung)
ggsurvplot(fit, data = lung, censor.shape="|", censor.size = 4)
ggsurvplot(
fit,
data = lung,
size = 1, # change line size
palette =
c("#E7B800", "#2E9FDF"),# custom color palettes
conf.int = TRUE, # Add confidence interval
pval = TRUE, # Add p-value
risk.table = TRUE, # Add risk table
risk.table.col = "strata",# Risk table color by groups
legend.labs =
c("Male", "Female"), # Change legend labels
risk.table.height = 0.25, # Useful to change when you have multiple groups
ggtheme = theme_bw() # Change ggplot2 theme
)