Survival analysis using R/python/stata : Demonstrative Session
A word about R
RStudio is an integrated development environment (IDE) for R. Basically, it’s a place where you can easily use the R language, visualize tables and figures and even run all your statistical analyses. We recommend using it instead of the traditional command line as it provides great visual aid and a number of useful tools that you will learn more about over the course of this workshop.
model <- lm(formula, data, ...)where ... symbolizes other options to pass to lm(). The function does not have an x/y interface, where we might pass in our outcome as y and our predictors as x.
To estimate with regularization, the second case, a Bayesian model can be fit using the package:
model <- stan_glm(formula, data, family = "gaussian", ...)In this case, the other options passed via ... would include arguments for the prior distributions of the parameters as well as specifics about the numerical aspects of the model. As with lm(), only the formula interface is available.
- R packages extend the functionality of R by providing additional functions, and can be downloaded for free from the internet.
Getting Help
Google it!: Try Googling generalized versions of any error messages you get. That is, remove text that is specific to your problem (names of variables, paths, datasets, etc.). You’d be surprised how many other people have probably had the same problem and solved it.
Stack Overflow: There are over 100,000 questions tagged with “R” on SO. Here are the most popular ones, ranked by vote. Always search before asking, and make a reproducible example if you want to get useful advice. This is a minimal example that allows others who are trying to help you to see the error themselves.
Read package vignettes. For example, see the dplyr CRAN page, scroll about halfway down to see the introduction to dplyr vignette.
General R Resources
- TryR: An interactive, browser-based R tutor
- Swirl: An R package that teaches you R (and statistics!) from within R
- Jenny Bryan’s Stat 545 “Data wrangling, exploration, and analysis with R” course material: An excellent resource for learning R, dplyr, and ggplot2
- DataCamp’s free introduction to R
- More DataCamp courses (UVA’s education benefits will cover these!).
- RStudio’s printable cheat sheets
- Rseek: A custom Google search for R-related sites
- Bioconductor vignettes, workflows, and course/conference materials
dplyr resources
ggplot2 resources
- The official ggplot2 documentation
- The ggplot2 book, edition 1, by the developer, Hadley Wickham
- New version of the ggplot2 book, freely available on GitHub
- The ggplot2 Google Group (mailing list, support forum)
- LearnR: A blog with a good number of posts describing how to reproduce various kind of plots using ggplot2
- SO questions tagged with ggplot2
- A catalog of graphs made with ggplot2, complete with accompanying R code
- RStudio’s ggplot2 cheat sheet
Markdown / RMarkdown resources
- Basic Markdown + RMarkdown reference
- In-browser markdown editors:
- Minimal: bioconnector.github.io/markdown-editor
- Better: stackedit.io, dillinger.io
- A good markdown reference
- A good 10-minute markdown tutorial
- RStudio’s RMarkdown Cheat Sheet and RMarkdown Reference Sheet
- The RMarkdown documentation has an excellent getting started guide, a gallery of demos, and several articles illustrating advanced usage.
- The knitr website has lots of useful reference material about how knitr works, options, and
library(reticulate)use_python("C:/Users/r1953/AppData/Local/Programs/Python/Python313/python.exe", required = TRUE)
use_virtualenv("~/.virtualenvs/r-reticulate", required = TRUE)
#py_config()
#py_install("scikit-learn")
#py_install("pandas")
#py_install("numpy")
#py_install("matplotlib")Key variables
- failure - Indicates whether the individual has experienced the event or not. For example: event is coded as 1 and no event as 0.
- event - The date that the individual experiences the event.
- origin - The date that defines when the time is zero. This is optional (but we think it makes sense to give the same date here as enter). However, if we want to attain age as the timescale, origin is specified as the date of birth.
- enter - The date that the individual becomes at risk, i.e. enters the observational period. For example, if you have a follow-up period, enter is specified as the start date of that period.
- exit - The date that the individual exits the study, i.e. the latest time that the individual is at risk. This is optional (the default is that the individual is removed after the event has occurred). However, it is useful if you want to specify the end date of the follow-up period.
- id - Identification (id) number.
Back to Todays Business
basic definitions in survival analysis
- Survival analysis lets you analyze the rates of occurrence of events over time, without assuming the rates are constant.
- Generally, survival analysis lets you model the time until an event occurs, In the medical world, we typically think of survival analysis literally ,tracking time until death.
- But, it’s more general that survival analysis models time until an event occurs (any event).
Examples
- Survival times are generally not symmetrically distributed.
- Usually the data is positively skewed and it will be unreasonable to assume that of this type have a normal distribution. - Survival times are frequently censored.
The survival time of an individual is said to be censored when the end-point of interest has not been observed for that individual.
Example of the distribution of follow-up times according to event status:
- Censoring is a type of missing data problem unique to survival analysis.
- This happens when you track the sample/subject through the end of the study and the event never occurs.
- This could also happen due to the sample/subject dropping out of the study for reasons other than death, or some other loss to followup.
- The sample is censored in that you only know that the individual survived up to the loss to followup, but you don’t know anything about survival after that.
A subject may be censored due to:
Loss to follow-up
Withdrawal from study
No event by end of fixed study period
Specifically these are examples of right 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.
illustrating the impact of censoring:
How would we compute the proportion who are event-free at 10 years?
whats happening
Subjects 6 and 7 were event-free at 10 years.
Subjects 2, 9, and 10 had the event before 10 years.
Subjects 1, 3, 4, 5, and 8 were censored before 10 years, 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.
Theoretical Rationale
To analyze survival data, we need to know the observed time \(Y_i\) and the event indicator \(\delta_i\). For subject \(i\):
- Observed time \(Y_i = \min(T_i, C_i)\) where \(T_i\) = event time and \(C_i\) = censoring time
- Event indicator \(\delta_i\) = 1 if event observed (i.e. \(T_i \leq C_i\)), = 0 if censored (i.e. \(T_i > C_i\))
The distribution function \(F(t)\) is used to describe chances of time of survival being less than a given value, t. In some cases, the cumulative distribution function is of interest and can be obtained as follows:
\[F(t)=P(T\le t)=\int_{t}^{\infty}f(u)\]
- Interest also tends to focus on the survival or survivorship function which in a study is the chances of an individual surviving after time \(t\) and also given by the formula
probability that an individual survives beyond any given time
\[ S(t) = Pr(T>t) \]
\(S(t)\) monotonically decreasing function with \(S(0) = 1\) and \(S(\infty) = \text{lim}_{t \rightarrow \infty} S(t) = 0\).
Hazard function
Suppose we have \(R (t)\) (set at risk) that has individuals who are prone to dying by time \(t\), the chances of an individual in that set to die in a given interval \([t, t + \delta t)\) is given by the following formula, where \(h(t)\) is the hazard rate and is defined as:
\[h(t) = \lim_{\delta t \rightarrow 0} \frac{P(t < T \le t+\delta t | T > t)}{\delta t}\] The hazard function’s shape can be any strictly positive function and it changes based on the specific survival data provided.
Relationship between h(t) and S(t)
we know that \(f(t) = - \frac{d}{dt} S(t)\) hence equation simplifies to
\[h(t)=\frac{f(t)}{S(t)} =\frac{- \frac{d}{dt} S(t)}{S(t)}= - \frac{d}{dt} [\log S(t)]\]
Taking intergrals both sides the above reduces to: \[H(t)= -\log S(t)\]
where \(H(t)=\int_{t}^{t} h(u) du\) ,is the cumulative risk of a individual dying by time t. Since the event is death, then H(t) summarises the risk of death up to time t, assuming that death has not occurred before t. The survival function is also approximately simplified as follows. \[ S(t) = e^{-H(t)} \approx 1 -H(t) \text{ when H(t) is small. }\]
Estimating the survivor function
Example : Pulmonary metastasis (Assuming no censoring)
One complication in the management of patients with a malignant bone tumour, or osteosarcoma, is that the tumour often spreads to the lungs. This pulmonary metastasis is life-threatening. In a study concerned with the treatment of pulmonary metastasis arising from osteosarcoma, Burdette and Gehan (1970) give the following survival times, in months, of eleven male patients.
\[\hat{S}(t)= \frac{Number~of~individuals~with~survival~time > t}{Number~of~individuals~in~the~dataset}\]
\[11~ 13~ 13 ~13 ~13 ~13~ 14~ 14~ 15~ 15 ~17\] \[\hat{S}(0)=\frac{11}{11}=1\]
\[\hat{S}(11)=\frac{10}{11}=0.9090909\]
\[\hat{S}(13)=\frac{4}{11}=0.4545455\]
\[\hat{S}(14)=\frac{3}{11}=0.2727273\]
\[\hat{S}(15)=\frac{1}{11}=0.09090909\]
If there are \(r\) times of deaths among individuals, such that \(r\leq n\) and \(n\) is the number of individuals with observed survival times. Arranging these times in from the smallest to the largest,the \(j\)-th death time is noted by \(t_{(j)}\) , for \(j = 1, 2, \cdots , r\), such that the \(r\) death times ordred are \[ t_{1}<t_{2}< \cdots < t_{m}\] .
Let \(n_j\), for \(j = 1, 2, \ldots, r\), denote the number of individuals who are still alive before time \(t(j)\), including the ones that are expected to die at that time. Additionally, let \(d_j\) denote the number of individuals who die at time \(t(j)\). The estimate for the product limit can be expressed in the following form:
\[\hat{S}(t) = \prod_{j=1}^k \, \left(1-\frac{d_j}{r_j}\right)\]
To survive until time \(t\), an individual must start by surviving till \(t(1)\), and then continue to survive until each subsequent time point \(t(2), \ldots, t(r)\). It is assumed that there are no deaths between two consecutive time points \(t(j-1)\) and \(t(j)\). The conditional probability of surviving at time \(t(i)\), given that the individual has managed to survive up to \(t(i-1)\), is the complement of the proportion of the individuals who die at time \(t(i)\), denoted by \(d_i\), to the new individuals who are alive just before \(t(i)\), denoted by \(n_i\). Therefore, the probability that is conditional of surviving at time \(t(i)\) is given by \(1 - \frac{d_i}{n_i}\).
The variance of the estimator is given by \[\text{var}(\hat{S}(t)) = [\hat{S}(t)]^2 \sum_{j=1}^k \frac{d_j}{(r_j-d_j) r_j}\]
The corresponding standard deviation is therefore given by: \[\text{s.e}(\hat{S}(t)) = [\hat{S}(t)]\left[\sum_{j=1}^k \frac{d_j}{(r_j-d_j) r_j}\right]^{\frac{1}{2}}\]
The Kaplan-Meier curve illustrates the survival function. It’s a step function illustrating the cumulative survival probability over time. The curve is horizontal over periods where no event occurs, then drops vertically corresponding to a change in the survival function at each time an event occurs.
Example
In trials involving contraceptives, prevention of pregnancy is an obvious criterion for acceptability. However, modern contraceptives have very low failure rates, and so the occurrence of bleeding disturbances, such as amenorrhoea (the prolonged absence of bleeding), irregular or prolonged bleeding, become important in the evaluation of a particular method of contraception. To promote research into methods for analysing menstrual bleeding data from women in contraceptive trials, the World Health Organisation made available data from clinical trials involving a number of different types of contraceptive (WHO, 1987). Part of this data set relates to the time from which a woman commences use of a particular method until discontinuation, with the discontinuation reason being recorded when known. The data in Table 1.1 refer to the number of weeks from the commencement of use of a particular type of intrauterine device (IUD), known as the Multiload 250, until discontinuation because of menstrual bleeding problems. Data are given for 18 women, all of whom were aged between 18 and 35 years and who had experienced two previous pregnancies. Discontinuation times that are censored are labelled with an asterisk. In this example, the time origin corresponds to the first day in which a woman uses the IUD, and the end-point is discontinuation because of bleeding problems. Some women in the study ceased using the IUD because of the desire for pregnancy, or because they had no further need for a contraceptive, while others were simply lost to follow-up. These reasons account for the censored discontinuation times of 13, 18, 23, 38, 54 and 56 weeks. The study protocol called for the menstrual bleeding experience of each woman to be documented for a period of two years from the time origin. For practical reasons, each woman could not be examined exactly two years after recruitment to determine if they were still using the IUD, and this is why there are three discontinuation times greater than 104 weeks that are right-censored.
\[ \begin{align} \hat{S}(t_j) &=\prod_{j=1}^k \, \left(1-\frac{d_j}{r_j}\right)\\ &= S(t_{j-1})\left(1-\frac{d_j}{r_j}\right)\\ \end{align} \] \[ \begin{align} \hat{S}(0) &= 1*\left(1-\frac{0}{18}\right)=1\\ \end{align} \]
\[ \begin{align} \hat{S}(10) &= 1*\left(1-\frac{1}{18}\right)=0.9444444\\ \end{align} \]
\[ \begin{align} \hat{S}(19) &= 0.9444444*\left(1-\frac{1}{15}\right)=0.8814814\\ \end{align} \]
\[.............\]
quietly import delimited sample
stset time , failure(status)
sts list
## Survival-time data settings
##
## Failure event: status!=0 & status<.
## Observed time interval: (0, time]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 18 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 18 observations remaining, representing
## 9 failures in single-record/single-failure data
## 1,046 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 107
##
##
## Failure _d: status
## Analysis time _t: time
##
## Kaplan–Meier survivor function
##
## At Survivor Std.
## Time risk Fail Lost function error [95% conf. int.]
## ------------------------------------------------------------------------
## 10 18 1 0 0.9444 0.0540 0.6664 0.9920
## 13 17 0 1 0.9444 0.0540 0.6664 0.9920
## 18 16 0 1 0.9444 0.0540 0.6664 0.9920
## 19 15 1 0 0.8815 0.0790 0.6019 0.9691
## 23 14 0 1 0.8815 0.0790 0.6019 0.9691
## 30 13 1 0 0.8137 0.0978 0.5241 0.9363
## 36 12 1 0 0.7459 0.1107 0.4536 0.8970
## 38 11 0 1 0.7459 0.1107 0.4536 0.8970
## 54 10 0 1 0.7459 0.1107 0.4536 0.8970
## 56 9 0 1 0.7459 0.1107 0.4536 0.8970
## 59 8 1 0 0.6526 0.1303 0.3438 0.8432
## 75 7 1 0 0.5594 0.1412 0.2564 0.7804
## 93 6 1 0 0.4662 0.1452 0.1830 0.7097
## 97 5 1 0 0.3729 0.1430 0.1209 0.6310
## 104 4 0 1 0.3729 0.1430 0.1209 0.6310
## 107 3 1 2 0.2486 0.1392 0.0468 0.5313
## ------------------------------------------------------------------------Life table
Let’s see what is happening here
Based on the grouped data, we will estimate the survival curve using the lifetab() in the KMsurv package. See the help page ?lifetab for a description of the arguments and example
- \(n'_j\) adjusted number of subjects that were at risk within a time interval
- \(n_j\)= number of subjects that were enrolled at time interval i
- \(c_j\) = number of subjects that were censored within the time interval
- \(d_j\) = number of subjects that experienced the event during the time interval
\[S(t_i) = S(t_{j-1})(1-\frac{d_j}{n_j})\]
Given the problem of contrasting two or more survival functions,for instance survival times between male and female individuals in the ICU. Let \[ t_{1}<t_{2}< \cdots < t_{r}\]
Let \(t_i\) be the unique times of death observed among the individuals, found by joining all groups of interest. For group \(j\),\ let \(d_{ij}\) denote the number of deaths at time \(t_i\), and\ let \(n_{ij}\) denote the number at risk at time \(t_i\) in that group. Let \(d_i\) denote the total number of deaths at time \(t_i\) across all groups, and\
the expected number of deaths in group \(j\) at time \(t_i\) is: ,
\[E(d_{ij}) = \frac{n_{ij} \, d_i}{n_i} = n_{ij} \left(\frac{d_i}{n_i}\right) \]
At time \(t_i\), suppose there are \(d_i\) deaths and \(n_i\) individuals at risk in total, with \(d_{i0}\) and \(d_{i1}\) deaths and \(n_{i0}\) and \(n_{i1}\) individuals at risk in groups 0 and 1, respectively, such that \(d_{i0} + d_{i1} = d_i\) and \(n_{i0} + n_{i1} = n_i\). Such data can be summarized in a \(2 \times 2\) table at each death time \(t_i\).
Given that the null hypothesis is true, the number of deaths is expected to follow the hypergeometric distribution, and therefore: \[E(d_{i0}) =e_{i0}= \frac{n_{i0} \, d_i}{n_i} = n_{i0} \left(\frac{d_i}{n_i}\right)\]
\[\text{Var}(d_{i0}) = \frac{n_{i0} \, n_{i1} \, d_i(n_i-d_i)}{n_{i}^2 (n_{i}-1)}\]
the statistic \(U_L\) is given by \[U_L=\sum^r_{i=1}(d_{i0}-e_{i0})\] so that the variance of \(U_L\) is \[Var(U_L)=\sum^r_{j=1}v_{i0}=V_L\] which then follows that : \[\frac{U_L}{\sqrt{V_L}} \sim N(0,1)\] and squaring results in \[\frac{U^2_L}{V_L}\sim \chi^2_1\]
The model is semi-parametric in nature since no assumption about a probabilty distribution is made for the survival times. The baseline model can take any form and the covariate enter the model linearly (Fox,2008). The model can thus be represented as :
\[h(t|X) = h_0(t) \exp(\beta_1 X_{1} + \cdots + \beta_p X_{p})=h_0(t)\text{exp}^{(\beta^{T} X)}\]
In the above equation, \(h_0(t)\) is known as the baseline hazard function, which represents the hazard function for a individual when all the included variables in the model are zero. On the other hand, \(h(t|X)\) represents the hazard of a individual at time \(t\) with a covariate vector \(X=(x_1,x_2,\ldots,x_p)\) and \(\beta^T=(\beta_1,\beta_2,\ldots,\beta_p)\) is a vector of regression coefficients.
The partial likelihood
Given that \(t(1) < t(2) < \ldots < t(r)\) denote the \(r\) ordered death times. The partial likelihood is given by :
\[L(\beta) = \prod_{i=1}^{n} \left[\frac{\text{exp}^{\beta ^{T} X_i}}{ \sum_{\ell\in R(t_{(i)}}\text{exp}^{\beta ^{T} X_\ell}}\right]^{\delta_i}\]
Maximising the logarithmic of the likelihood function is more easier and computationally efficient and this is generally given by:
\[\log L(\beta)= \sum_{i=1}^{n} \delta_i \left[ \beta ^{T} X_i - \log \left(\sum_{\ell \in R(t_{(i)}}\text{exp}^{\beta ^{T} X_\ell}\right) \right]\]
Six types of residuals are studied in this thesis: Cox-Snell, Modified Cox-Snell, Schoenfeld, Martingale, Deviance, and Score residuals.
Cox-Snell Residuals
Cox-Snell definition of residuals given by Cox and Snell (1968) is the most common residual in survival analysis. The Cox-Snell residual for the \(ith\) individual, \(i = 1, 2, \cdots , n\), is given by
\[r_{Ci}=\text{exp}(\mathbf{\hat{\beta}^{T} x_i})\hat{H}_0(t_i)\]
where \(\hat{H}_0(t_i)\) is an estimate of the baseline cumulative hazard function at time \(t_i\). It is sometimes called the Nelson-Aalen estimator.
Martingale residuals
These are useful in determing the functional form of the covariates to be included in the model. If the test reveals that the covariate can not be included linearly then there is need for such a covariate to be transformed . The martingale residuals are represented in the following form
\[r_{Mi}=\delta_i - r_{Ci}\]
Deviance Residuals
The skew range of Martingale residual makes it difficult to use it to detect outliers. The deviance residuals are much more symmetrically distributed about zero and are defined by
\[r_{Di}=\text{sgn}(r_{Mi})\left[-2\{r_{Mi}+\delta_i\log\left(\delta_i-r_{Mi}\right)\}\right]^{\frac{1}{2}}\]
Here, \(r_{Mi}\) represents the martingale residual for the \(i\)-th individual, and the function \(\text{sgn}(\cdot)\) denotes the sign function. Specifically, the function takes the value +1 if its argument is positive and -1 if negative.
Schoenfield residuals
Schoenfeld residuals are a useful tool for examining and testing the proportional hazard assumption, detecting leverage points, and identifying outliers. They can be calculated as follows:
\[r_{Sji}=\delta_i\{x_{ji}-\hat{a}_{ji}\}\]
where \(x_{ji}\) is the value of the \(jth\) explanatory variable,\(j = 1, 2, \cdots , p\), for the \(ith\) individual in the study,
\[\hat{a}_{ji}=\frac{\sum_{\ell \in R(t_i)}x_{j\ell}\text{exp}(\mathbf{\hat{\beta}^{T} x_{\ell}})}{\sum_{\ell \in R(t_i)}\text{exp}(\mathbf{\hat{\beta}^{T} x_{\ell}})}\]
Examples in R
functions
The core functions we’ll use out of the survival package include:
Surv(): Creates a survival object.survfit(): Fits a survival curve using either a formula, of from a previously fitted Cox model.coxph(): Fits a Cox proportional hazards regression model.
Other optional functions you might use include:
cox.zph(): Tests the proportional hazards assumption of a Cox regression model.survdiff(): Tests for differences in survival between two groups using a log-rank / Mantel-Haenszel test.1
Surv() creates the response variable, and typical usage takes the time to event,[^time2] and whether or not the event occured (i.e., death vs censored). survfit() creates a survival curve that you could then display or plot. coxph() implements the regression analysis, and models specified the same way as in regular linear models, but using the coxph() function.
Data description
These data come from patients who were admitted at a tertiary hospital due to acute stroke. They were treated in the ward and the status (dead or alive) were recorded. The variables are:
setup
In this section, we will use the following packages which have already been installed in cloud.
- reading in data in R using read_csv, read.csv etc
take a look at the dataset
Data wrangling
- data will not always come in the neatest case scenario hence you need to work on it through processes we call data wrangling and munging.
Creating a Survival Object
The survival object is created by the function survival::Surv, which typically requires two arguments: event and time. The survival object will be used as the outcome by the survival analysis methods we explore.
quietly import delimited stroke2
stset time2 , failure(status2)
## Survival-time data settings
##
## Failure event: status2!=0 & status2<.
## Observed time interval: (0, time2]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 213 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 213 observations remaining, representing
## 48 failures in single-record/single-failure data
## 1,379 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 43Estimating the Survival Function: Kaplan-Meier Estimator
The Kaplan-Meier (KM) Estimator is a non-parametric method that estimates the survival probabilities at each time an event occurs. We will use the function survival::survfit(), which uses the KM Estimator, to estimate survival probabilities from our data.
survfit requires two arguments:
- A formula object where the outcome is a survival object
- A data frame
The survival probabilities for all patients:
Plotting the overal Survival Function
quietly import delimited stroke2
stset time2 , failure(status2)
sts graph, survival
quietly graph export overal.svg, replace
## Survival-time data settings
##
## Failure event: status2!=0 & status2<.
## Observed time interval: (0, time2]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 213 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 213 observations remaining, representing
## 48 failures in single-record/single-failure data
## 1,379 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 43
##
##
## Failure _d: status2
## Analysis time _t: time2Comparing Groups: Stroke Type
- this will give us two tables ,relating to two factors that we have in the data , fill in the missing gaps.
The KM estimate provides the survival probabilities. We can plot these probabilities to look at the trend of survival over time. The plot provides
- survival probability on the \(y-axis\)
- time on the \(x-axis\)
quietly import delimited stroke2
stset time2 , failure(status2)
sts graph , by(stroke_type)
quietly graph export KM.svg, replace
## Survival-time data settings
##
## Failure event: status2!=0 & status2<.
## Observed time interval: (0, time2]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 213 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 213 observations remaining, representing
## 48 failures in single-record/single-failure data
## 1,379 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 43
##
##
## Failure _d: status2
## Analysis time _t: time2plt.close('all')
import pandas as pd
from lifelines import KaplanMeierFitter
from matplotlib import pyplot as plt
# get data
url = "stroke2.csv"
stroke2 = pd.read_csv(url)
# fit our data to Kaplan-Meier estimates
T = job_retention["time2"]
E = job_retention["status2"]
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed = E)
# split into HS and IS
HS = (stroke2["stroke_type"] == "HS")
# set up plot
survplot = plt.subplot()
# plot HS survival function
kmf.fit(T[HS], event_observed = E[HS],
label = "HS")
kmf.plot_survival_function(ax = survplot)
# plot IS survival function
kmf.fit(T[~HS], event_observed = E[~HS],
label = "IS")
kmf.plot_survival_function(ax = survplot)
# show survival curves by stroke_type
plt.show()- Clearly from the plot we can tell that patients with stroke-type=IS (blue) survived longer than the other group.
- There is a significant difference in survival times between the groups (p<0.05)
Comparing Groups: Diabetes
We can perform the Kaplan-Meier estimates for variable dm too:
quietly import delimited stroke2
quietly stset time2 , failure(status2)
sts graph , by(dm)
quietly graph export dm.svg, replace
## Failure _d: status2
## Analysis time _t: time2Making the plots fancy
- Clearly from the plot we can tell that patients without diabetes melitus survived longer than those with diabetes, however the difference is not statistically significant.
Try it Yourself for referral_from and sex
There are a number of available tests to compare the survival estimates between groups based on KM. The tests include:
- log-rank (default)
- peto-peto test
Log-rank test
Null and Alternative Hypothesis
\(H_o : S_1(t) = S_2(t), \forall t\)
\(H_a : \exists t : S_1(t) \neq S_2(t)\)
The hypotheses above are as follows
\(H_o:\) There is no significant difference in survival between the groups.
\(H_a:\) There is a significant difference in survival between the groups.
We will consider p < 0.05 to indicate statistical significance.
Performing the test
quietly import delimited stroke2
stset time2 , failure(status2)
sts test stroke_type ,logrank
## Survival-time data settings
##
## Failure event: status2!=0 & status2<.
## Observed time interval: (0, time2]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 213 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 213 observations remaining, representing
## 48 failures in single-record/single-failure data
## 1,379 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 43
##
##
## Failure _d: status2
## Analysis time _t: time2
##
## Equality of survivor functions
## Log-rank test
##
## | Observed Expected
## stroke_type | events events
## ------------+-------------------------
## HS | 31 24.18
## IS | 17 23.82
## ------------+-------------------------
## Total | 48 48.00
##
## chi2(1) = 4.51
## Pr>chi2 = 0.0338And for the survival estimates based on diabetes status:
quietly import delimited stroke2
quietly stset time2 , failure(status2)
sts test dm ,logrank
## Failure _d: status2
## Analysis time _t: time2
##
## Equality of survivor functions
## Log-rank test
##
## | Observed Expected
## dm | events events
## ------+-------------------------
## no | 35 29.77
## yes | 13 18.23
## ------+-------------------------
## Total | 48 48.00
##
## chi2(1) = 2.54
## Pr>chi2 = 0.1108And for the survival estimates based on diabetes status:
The survival estimates between the surv_data types (IS vs HS groups) are different at the level of \(5\%\) significance (p-value = 0.03).
The survival estimates between patients with and without diabetes (dm status yes vs no groups) are not different (p-value = 0.1).
There is a family of test based on a comparison of observed and expected counts at each distinct failure time, which differ in terms of the weights assigned to each time as shown in the table below
| Name | Weight |
|---|---|
| Mantel-Haenszel | 1 |
| Wilcoxon | ni |
| Tarone-Ware | √ni |
| Peto-Peto-Prentice | S(ti) |
| Fleming-Harrington | S(ti)p (1-S(ti))q |
The most popular of these is the Wilcoxon test -actually an extension of Wilcoxon’s well-known non-parametric test- proposed by Gehan and Breslow, which gives more weight to early failures. Stata can compute all four using the options wilcoxon, tware, peto and fh(p, q). R implements three using a parameter rho (p in our notation), with rho=0 for log-rank, rho=1 for Peto-Peto, and rho=p for Fleming-Harrington with q=1. The tests using the survival as weight treat it as left-continuous. ## Cox PH General model
- We have seen that , logrank/wilcoxon test fails to account for confounders….we cant account for numerical data
- Suppose that 2 groups of patients receive standard or new treatment and let \(h_S(t)\) and New treatment and let \(h_N(t)\) be the hazards of death at time t.
- The hazard of death at time t for a patient on new treatment is proportional to the hazard at the same time for a patient on the standard treatment i.e
\[h_N(t) =\Phi h_S(t)\]
- \(\Phi\) is the ratio of the hazard of death at any time for an individual on the new treatment relative to an individual in a standard treatment hence \(\phi\) is a relative hazard or the hazard ratio.
- The hazard can not be negative, hence $= ^{}=>=log() $
\[h_N(t) =\exp^{\beta} h_S(t)\]
Generalizing
- let X be an indicator variable , which takes the value zero if an individual is on the standard drug and 1 if on new drug.
- If \(x_i\) is the value of X for the \(i^{th}\) individual in the study , \(i=1,2,3,....,n\) , the hazard function is given by :
\[h_i(t) = e^{\beta x_i}h_0(t)\] where \(x_i = 1\) if the \(i^{th}\) individual is on new treatment and \(0\) otherwise.
Introducing more variables
The Cox model is expressed by the hazard function denoted by \(h(t)\). This model can be used to fit univariable and multivariable regression models that have survival outcomes. The hazard function can be interpreted as the risk of dying at time t. It can be estimated as follow:
\[h(t, X_{i}) = h_{0}(t)exp(\beta_{1}X_{i,1} + ... +\beta_{p}X_{i,p})= h_{0}(t)e^{ \sum_{j=1}^{p} \beta_{j}X_{i,j}} \]
where:
- \(h(t,X_i)\) is the hazard, the instantaneous rate at which events occur.
- \(h_{0}(t)\) is called the baseline hazards (when all X’s are equal to 0), depends on \(t\)
- \(X = (X_{1}, X_{2},..., X_{p})\) explanatory/predictor variables
- \(e^{ \sum_{i=1}^{p} \beta_{i}X_{i}}\), depends only on X’s, called time-independent.
Because the baseline hazard \(h_{0}(t)\) is an unspecified function, the Cox model us a semiparametric model.
Advantages of the model: “robust” model, so that the results from using the Cox model will closely approximate the results for the correct parametric model.
The Cox model can be written as a multiple linear regression of the logarithm of the hazard on the variables \(X_{i}\), with the baseline hazard, \(h_{0}(t)\), being an ‘intercept’ term that varies with time.
\[log(h(t, X_{i})) = log(h_{0}(t)) + \log{e^{\sum_{j=1}^{p} \beta_{j}X_{i,j}}}=log(h_{0}(t)) + \sum_{j=1}^{p} \beta_{j}X_{i,j}\]
\[log \frac{h(t, X_{i})}{h_{0}(t)} =\sum_{j=1}^{p} \beta_{j}X_{i,j}=\beta_{1}X_{i,1} + ... +\beta_{p}X_{i,p}\]
Giving a linear model for the logarithm of the hazard ratio.
- for one unit increase in \(x_i\) the log hazard changes in which direction?
\[\frac{h(t, X_{i})}{h_{0}(t)} =\exp(\beta_{1}X_{i,1} + ... +\beta_{p}X_{i,p})\]
A hazard ratio above 1 indicates a covariate that is positively associated with the event probability, and thus negatively associated with the length of survival.
In summary,
- HR = 1 : No effect
- HR < 1: Reduction in the hazard
- HR > 1: Increase in Hazard
As a note, in clinical studies, a covariate with hazard ratio :
- greater than 1 (i.e.: b>0) is called bad prognostic factor.
- smaller than 1 (i.e.: b<0) is called good prognostic factor.
As a consequence, a major assumption of this model is that the \(HR\) is constant over time because it is independent of time. Or equivalently that the hazard for one individual is proportional to the hazard for any other individual, where the proportionality constant is independent of time.
It is possible, nevertheless, to consider X’s which do involve t. Such X’s are called time-dependent variables. If time-dependent variables are considered, the Cox model form may still be used, but such a model no longer satisfies the PH assumption, and is called the extended Cox model.
- The coxph() function uses the same syntax as lm(), glm(), etc. The response variable you create with Surv() goes on the left hand side of the formula, specified with a ~. Explanatory variables go on the right side.
Cox PH model with with a continous variable only
Model with a covariate
Suppose that a Cox regression model contains a single continuous variable X, so that the hazard function for the \(ith\) of n individuals, for whom X takes the value \(x_i\), is \[h_i(t) = e^{\beta x_i}h_0(t)\]
The coefficient of \(x_i\) in this model can then be interpreted as the logarithm of a hazard ratio. Specifically, consider the ratio of the hazard of death for an individual for whom the value \(x + 1\) is recorded on \(X\), relative to one for whom the value x is obtained. This is
\[\frac{\exp{\beta(x+1)}}{\exp(\beta x)} =\exp ^ \beta\]
- and so \(\hat{\beta}\) in the fitted Cox regression model is the estimated change in the logarithm of the hazard ratio when the value of \(X\) is increased by one unit.
quietly import delimited stroke2
quietly stset time2 , failure(status2)
stcox gcs , noshow
## Iteration 0: Log likelihood = -201.70797
## Iteration 1: Log likelihood = -189.43801
## Iteration 2: Log likelihood = -189.15565
## Iteration 3: Log likelihood = -189.15553
## Refining estimates:
## Iteration 0: Log likelihood = -189.15553
##
## Cox regression with Breslow method for ties
##
## No. of subjects = 213 Number of obs = 213
## No. of failures = 48
## Time at risk = 1,379
## LR chi2(1) = 25.10
## Log likelihood = -189.15553 Prob > chi2 = 0.0000
##
## ------------------------------------------------------------------------------
## _t | Haz. ratio Std. err. z P>|z| [95% conf. interval]
## -------------+----------------------------------------------------------------
## gcs | .8423505 .0289264 -5.00 0.000 .7875216 .9009966
## ------------------------------------------------------------------------------Stata reports hazard ratios unless you specify the option nohr. R reports log-relative risks, but also exponentiates the coefficients to obtain hazard ratios.
When we look at the results for gcs, we see that the hazard ratio (HR) is 0.8423. Thus, for each unit increase in gcs, the hazard of death decreases.
The association is statistically significant, as reflected in the p-value (0.000) and the 95% confidence intervals (0.7875216 -.9009966).
Summary The higher the Glasgow Coma Scale, the lower the risk of dying (HR=0.8423). The association is statistically significant (95% CI=0.7875216 -0.9009966).
Cox PH model with categorical variable stroke type variable only
Model with a factor
- When individuals fall into one of m groups, \(m \geq 2\), which correspond to categories of an explanatory variable, the groups can be indexed by the levels of a factor. Under a Cox regression model, the hazard function for an individual in the jth group, \(j = 1,2,...,m\) is given by:
\[h_j(t) =exp(\delta_j)h_0(t)\]
where \(\delta_j\) is the effect due to the jth level of the factor, and \(h_0(t)\) is the baseline hazard function. This model is overparameterised, and so, we take \(\delta_1 = 0\). The baseline hazard function then corresponds to the hazard of death at time t for an individual in the first group. The ratio of the hazards at time t for an individual in the jth group, \(j \geq 2\), relative to an individual in the first group, is then \(\exp(\delta_j)\). Consequently, the parameter \(\delta_j\) is the logarithm of this relative hazard, that is
\[\delta_j = log {\frac{h_j(t)}{h_0(t)}}\]
The hazard ratio for a patient aged \(60–70\), relative to one aged less than 60, is \(e^{−0.065} = 0.94\), while that for a patient whose age is greater than 70, relative to one aged less than 60, is \(e^{1.824} = 6.20\). These results suggest that the hazard of death at any given time is greatest for patients who are older than 70, but that there is little difference in the hazard functions for patients in the other two age groups.
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
stcox i.stroke_type_f , noshow efron
## Iteration 0: Log likelihood = -200.80376
## Iteration 1: Log likelihood = -198.54323
## Iteration 2: Log likelihood = -198.54221
## Refining estimates:
## Iteration 0: Log likelihood = -198.54221
##
## Cox regression with Efron method for ties
##
## No. of subjects = 213 Number of obs = 213
## No. of failures = 48
## Time at risk = 1,379
## LR chi2(1) = 4.52
## Log likelihood = -198.54221 Prob > chi2 = 0.0334
##
## ------------------------------------------------------------------------------
## _t | Haz. ratio Std. err. z P>|z| [95% conf. interval]
## -------------+----------------------------------------------------------------
## stroke_typ~f |
## IS | .5157038 .1635591 -2.09 0.037 .2769719 .9602073
## ------------------------------------------------------------------------------The effect of stroke type is significantly related to survival (p-value = 0.0368), with better survival in Ischaemic stroke type as compared to the other type (hazard ratio of dying = 0.5157).
The model is statistically significant. That 0.03344 p-value of the model is really close to the p = 0.03 p-value we saw on the Kaplan-Meier nodel as well as the likelihood ratio test = 4.52 is close to the log-rank chi-square (4.5) in the Kaplan-Meier model.
\(e^{\beta_{1}}\) = \(e^{-0.6622}\) = 0.5157 is the hazard ratio - the multiplicative effect of that variable on the hazard rate (for each unit increase in that variable). Ischaemic stroke type patients have 0.588 (~ 60%) times the hazard of dying in comparison to haemorage.
Handling Ties
There are various options for handling ties. Cox’s original proposal relies on the discrete partial likelihood. A closely-related alternative due to Kalbfleisch and Prentice uses the marginal likelihood of the ranks. Both methods are computationally intensive. A good fast approximation is due to Efron, and a simpler and faster, though somewhat less accurate, method is due to Breslow and Peto.
- Stata implements all four using the options,
exactp,exactm,efronandbreslow. - The default is
breslowbut recommend you always useefron. - R implements all but the marginal likelihood, using the argument
tieswith possible values “efron”, “breslow”, and “exact”. Let us compare them all.
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
quietly stcox i.stroke_type_f
estimates store breslow
quietly stcox i.stroke_type_f, efron
estimates store efron
quietly stcox i.stroke_type_f, exactm
estimates store exactm
quietly stcox i.stroke_type_f, exactp
estimates store exactp
estimates table breslow efron exactm exactp
## Variable | breslow efron exactm exactp
## -------------+----------------------------------------------------
## stroke_typ~f |
## IS | -.650994 -.66222266 -.66247748 -.67401651
## ------------------------------------------------------------------As you can see, Efron’s approximation is closer to the exact partial likelihood than Breslow’s. [The marginal likelihood is even closer.]
Interactions
In statistical modelling, the effect of an interaction can only be investigated by adding the interaction term to a model that already contains the corresponding main effects.
Main effects model
Model with interaction
Likelihood ratio test
Main Effects model
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
stcox i.sex_f gcs , nohr efron
## Failure _d: status2
## Analysis time _t: time2
##
## Iteration 0: Log likelihood = -200.80376
## Iteration 1: Log likelihood = -188.03512
## Iteration 2: Log likelihood = -187.7172
## Iteration 3: Log likelihood = -187.71706
## Refining estimates:
## Iteration 0: Log likelihood = -187.71706
##
## Cox regression with Efron method for ties
##
## No. of subjects = 213 Number of obs = 213
## No. of failures = 48
## Time at risk = 1,379
## LR chi2(2) = 26.17
## Log likelihood = -187.71706 Prob > chi2 = 0.0000
##
## ------------------------------------------------------------------------------
## _t | Coefficient Std. err. z P>|z| [95% conf. interval]
## -------------+----------------------------------------------------------------
## sex_f |
## male | -.1323784 .3314712 -0.40 0.690 -.7820501 .5172933
## gcs | -.1731227 .0346288 -5.00 0.000 -.240994 -.1052514
## ------------------------------------------------------------------------------Interaction model
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
stcox gcs i.sex_f i.sex_f#c.gcs , nohr
## Failure _d: status2
## Analysis time _t: time2
##
## Iteration 0: Log likelihood = -201.70797
## Iteration 1: Log likelihood = -190.00572
## Iteration 2: Log likelihood = -188.38739
## Iteration 3: Log likelihood = -188.35868
## Iteration 4: Log likelihood = -188.35866
## Refining estimates:
## Iteration 0: Log likelihood = -188.35866
##
## Cox regression with Breslow method for ties
##
## No. of subjects = 213 Number of obs = 213
## No. of failures = 48
## Time at risk = 1,379
## LR chi2(3) = 26.70
## Log likelihood = -188.35866 Prob > chi2 = 0.0000
##
## ------------------------------------------------------------------------------
## _t | Coefficient Std. err. z P>|z| [95% conf. interval]
## -------------+----------------------------------------------------------------
## gcs | -.1405185 .0417787 -3.36 0.001 -.2224034 -.0586337
## |
## sex_f |
## male | .5915702 .6697937 0.88 0.377 -.7212013 1.904342
## |
## sex_f#c.gcs |
## male | -.0839106 .070241 -1.19 0.232 -.2215805 .0537593
## ------------------------------------------------------------------------------Likelihood Ratio test
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
quietly stcox i.sex_f gcs , nohr efron
estimates store m1
quietly stcox i.sex_f gcs i.sex_f#c.gcs , nohr efron
estimates store m2
lrtest m1 m2
## Likelihood-ratio test
## Assumption: m1 nested within m2
##
## LR chi2(1) = 1.46
## Prob > chi2 = 0.2267- is an interaction required for this model? (is it significant?)
Model Building
this is important when perfoming statistical analysis
- first build a model with all variables
We can tidy this a bit
- the estimate which is the log hazard. If you exponentiate it, you will get hazard ratio
- the standard error
- the p-value
- the confidence intervals for the log hazard
using rms package
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
encode dm, gen(dm_f)
stcox gcs stroke_type_f sex_f dm_f sbp dbp wbc , nohr efron
## Failure _d: status2
## Analysis time _t: time2
##
## Iteration 0: Log likelihood = -200.80376
## Iteration 1: Log likelihood = -186.1534
## Iteration 2: Log likelihood = -185.79147
## Iteration 3: Log likelihood = -185.79117
## Refining estimates:
## Iteration 0: Log likelihood = -185.79117
##
## Cox regression with Efron method for ties
##
## No. of subjects = 213 Number of obs = 213
## No. of failures = 48
## Time at risk = 1,379
## LR chi2(7) = 30.03
## Log likelihood = -185.79117 Prob > chi2 = 0.0001
##
## ------------------------------------------------------------------------------
## _t | Coefficient Std. err. z P>|z| [95% conf. interval]
## -------------+----------------------------------------------------------------
## gcs | -.1751635 .0390834 -4.48 0.000 -.2517656 -.0985615
## stroke_typ~f | -.1146484 .3485303 -0.33 0.742 -.7977553 .5684584
## sex_f | -.1479707 .3496481 -0.42 0.672 -.8332683 .537327
## dm_f | -.4584505 .3639157 -1.26 0.208 -1.171712 .2548112
## sbp | .0036524 .0069059 0.53 0.597 -.009883 .0171877
## dbp | -.0119206 .0119187 -1.00 0.317 -.0352808 .0114395
## wbc | .010463 .0389368 0.27 0.788 -.0658517 .0867778
## ------------------------------------------------------------------------------plt.close('all')
import pandas as pd
from lifelines import KaplanMeierFitter
from matplotlib import pyplot as plt
# get data
url = "stroke2.csv"
stroke2 = pd.read_csv(url)
# fit our data to Kaplan-Meier estimates
T = job_retention["time2"]
E = job_retention["status2"]
from lifelines import CoxPHFitter
# fit Cox PH model to
cph = CoxPHFitter()
cph.fit(job_retention, duration_col = 'time2', event_col = 'status2',
formula = "gcs + stroke_type+dbp+wbc+ sex + dm + sbp")# view results
cph.print_summary()We can create univariate models first
By using tbl_uvregression() we can generate simple univariable model for all covariates in one line of code. In return, we get the crude HR for all the covariates of interest.
- it is clear that
gcshas the least p-value hence can be included in the model first
The simple Cox PH model with covariate gcs shows that with each one unit increase in gcs, the crude log hazard for death changes by a factor of \(-0.175\).
lets tidy it up
When we exponentiate the log HR, the simple Cox PH model shows that with each one unit increase in gcs, the crude risk for death decreases for about \(16\%\) and the of decrease are between \(95\% CI (0.785, 0.898)\). The relationship between death and gcs is highly significant (p-value \(< 0.0001\)) when not adjusting for other covariates.
next up we add stroke type
lets test if stroke type is worth it
- The variable is not significant
we try another one
lets test if dm is worth it
- still not worth is it , we can go on and on…
lets do a backward elimination
- final model has gcs variable as we had anticipated
- Here the decision depends on context .
- It might not really be about only including significant variables in the model.
- Very few variables and stepwise model selection might not be really necessary
- One could go with a model with all variables to make
inference
The Cox proportional hazards model makes several assumptions. We use residuals methods to:
- check the proportional hazards assumption with the Schoenfeld residuals
- detect nonlinearity in relationship between the log hazard and the covariates using Martingale residual
- examining influential observations (or outliers) with deviance residual (symmetric transformation of the martinguale residuals), to examine influential observations
Testing proportional hazard
The proportional hazard assumption is supported by a non-significant relationship between residuals and time, and refuted by a significant relationship.
We can test with the Goodness of Fit (GOF) approach based on the residuals defined by Schoenfeld.
The idea behind the statistical test is that if the PH assumption holds for a particular covariate then the Schoenfeld residuals for that covariate will not be related to survival time.
For each covariate, the function cox.zph() correlates the corresponding set of scaled Schoenfeld residuals with time, to test for independence between residuals and time. Additionally, it performs a global test for the model as a whole. Stata computes the test using the original time scale. R computes it using the overall survival function as the time scale.
- we could use transform = “identity” , to get similar results as in stata.
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
encode dm, gen(dm_f)
quietly stcox stroke_type_f sbp dbp sex_f gcs dm_f wbc , schoenfeld(sch*) efron
stphtest, detail
stphtest, plot(gcs) msym(oh) name(plt1)
stphtest, plot(sbp) msym(oh) name(plt2)
stphtest, plot(dbp) msym(oh) name(plt3)
stphtest, plot(sex_f) msym(oh) name(plt4)
stphtest, plot(dm_f) msym(oh) name(plt5)
stphtest, plot(stroke_type_f) msym(oh) name(plt6)
graph combine plt1 plt2 plt3 plt4 plt5 plt6
quietly graph export all_multii.svg, replace
## Test of proportional-hazards assumption
##
## Time function: Analysis time
## --------------------------------------------------------
## | rho chi2 df Prob>chi2
## -------------+------------------------------------------
## stroke_typ~f | 0.08241 0.34 1 0.5594
## sbp | 0.07541 0.25 1 0.6178
## dbp | -0.05022 0.12 1 0.7265
## sex_f | 0.10355 0.57 1 0.4486
## gcs | -0.11238 0.51 1 0.4757
## dm_f | 0.14525 1.22 1 0.2692
## wbc | -0.05420 0.14 1 0.7052
## -------------+------------------------------------------
## Global test | 2.98 7 0.8865
## --------------------------------------------------------From the output above, the test is not statistically significant for each variable, and the global test is also not statistically significant. Therefore, we can assume the proportional hazards.
In the graphical diagnostic using the function ggcoxzph() [in the survminer package], the solid line is a smoothing spline fit to the plot, with the dashed lines representing a +/- 2-standard-error band around the fit. From the graphical inspection, there is no pattern with time. The assumption of proportional hazards appears to be supported for the covariates sex (which is, recall, a two-level factor, accounting for the two bands in the graph).
The overall chi-squared statistic of 12.76 on 9 d.f. indicates no significant departure from the proportional hazards assumption. The only variable that might deserve further scrutiny is time served, which has the largest chi-squared statistic, although it doesn’t reach the conventional five percent level. Just out of curiosity we can plot the scaled Schoenfeld residuals against time.
another approach log-log curves
Another approach is to graphically check the PH assumption by comparing -log–log survival curves. A log–log survival curve is simply a transformation of an estimated survival curve that results from taking the natural log of an estimated survival probability twice.
\(h(t, X) = h_{0}(t)e^{ \sum_{j=1}^{p} \beta_{j}X_{j}}\) which is equivalent to \(S(t,X) = [S_{0}(t)]^{e^{ \sum_{j=1}^{p} \beta_{j}X_{j}}}\)
Therefore, \[-ln(-ln(S(t, X)))\]
\[= -ln(-ln([S_{0}(t)]^{e^{ \sum_{j=1}^{p} \beta_{j}X_{j}}}))\] \[= -ln[-ln(S_{0}(t))] - ln[e^{ \sum_{j=1}^{p} \beta_{j}X_{j}}]\]
\[= - \sum_{j=1}^{p} \beta_{j} X_{j} - ln[-ln(S_{0}(t))]\]
Therefore, the corresponding log–log curves for these individuals are given as shown here, where we have simply substituted \(X_1\) and \(X_2\) for \(X\) in the previous expression for the log–log curve for any individual \(X\).
\[ln(-ln(S(t, X_1))) - ln(-ln(S(t, X_2)))\] \[= \sum_{j=1}^{p} \beta_{j} (X_{1j} - X_{2j})\]
The baseline survival function has dropped out, so that the difference in log–log curves involves an expression that does not involve time t. The above formula says that if we use a Cox PH model and we plot the estimated -log–log survival curves for two groups of individuals on the same graph, the two plots would be approximately parallel.
The distance between the two curves is the linear expression involving the differences in predictor values, which does not involve time. Note, in general, if the vertical distance between two curves is constant, then the curves are parallel.
plot
## function (x, y, ...)
## UseMethod("plot")
## <bytecode: 0x000001d5e5a273f0>
## <environment: namespace:base>The two curve cross, therefore this result suggests that the two groups in surv_data type do not satisfy the PH assumption.
To test influential observations or outliers, we can visualize either: the dfbeta values or the deviance residuals.
- dfbeta values
This plot produces the estimated changes in the coefficients divided by their standard errors. The comparison of the magnitudes of the largest dfbeta values to the regression coefficients suggests that none of the observations is terribly influential individually.
2) deviance residuals
The deviance residual is a normalized transformation of the martingale residual. These residuals should be roughly symmetrically distributed about zero with a standard deviation of 1.
Forest Plot
Multicollinearity
Coxsnell Residuals
quietly import delimited stroke2
quietly stset time2 , failure(status2)
encode stroke_type, gen(stroke_type_f)
encode sex, gen(sex_f)
encode dm, gen(dm_f)
quietly stcox stroke_type_f sbp dbp sex_f gcs dm_f wbc, nohr mgale(mg)
predict cs, csnell
stset cs, failure(status2)
sts generate H = na
line H cs cs, sort xlab(0 1 to 4) ylab(0 1 to 4)
drop mg
quietly graph export csnell.svg, replace
## Survival-time data settings
##
## Failure event: status2!=0 & status2<.
## Observed time interval: (0, cs]
## Exit on or before: failure
##
## --------------------------------------------------------------------------
## 213 total observations
## 0 exclusions
## --------------------------------------------------------------------------
## 213 observations remaining, representing
## 48 failures in single-record/single-failure data
## 48 total analysis time at risk and under observation
## At risk from t = 0
## Earliest observed entry t = 0
## Last observed exit t = 2.694111Lastly
Alternative Model selection Procedures
Instead of using automatic variable selection procedures, the following general strategy for model selection is recommended.
- The first step is to fit models that contain each of the variables one at a time. The values of −2logL for these models are then compared with that for the null model to determine which variables on their own significantly reduce the value of this statistic.
- The variables that appear to be important from Step 1 are then fitted together. In the presence of certain variables, others may cease to be im portant. Consequently, those variables that do not significantly increase the value of −2logL when they are omitted from the model can now be discarded. We therefore compute the change in the value of −2logL when each variable on its own is omitted from the set. Only those that lead to a significant increase in the value of −2logL are retained in the model. Once a variable has been dropped, the effect of omitting each of the remaining variables in turn should be examined.
- Variables that were not important on their own, and so were not under consideration in Step 2, may become important in the presence of others. These variables are therefore added to the model from Step 2, one at a time, and any that reduce −2logL significantly are retained in the model. This process may result in terms in the model determined at Step 2 ceasing to be significant.
- A final check is made to ensure that no term in the model can be omitted without significantly increasing the value of −2logL, and that no term not included significantly reduces −2logL.
Footnotes
Cox regression and the logrank test from
survdiffare going to give you similar results most of the time. The log-rank test is asking if survival curves differ significantly between two groups. Cox regression is asking which of many categorical or continuous variables significantly affect survival.↩︎