Survivametodl
Survivametodl
Terry Therneau
1 Introduction 3
1.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Survival data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Mathematical Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Survival curves 9
2.1 One event type, one event per subject . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Repeated events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Competing risks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3.1 Simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3.2 Monoclonal gammopathy . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4 Multi-state data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4.1 Myeloid data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5 Inuence matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.6 Dierences in survival . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.7 Robust variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.8 State space gures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.8.1 Further notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3 Cox model 43
3.1 One event type, one event per subject . . . . . . . . . . . . . . . . . . . . . . . . 43
3.2 Repeating Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3 Competing risks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.3.1 MGUS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.4 Multiple event types and multiple events per subject . . . . . . . . . . . . . . . . 57
3.4.1 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.4.2 Fits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.4.3 Timeline data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.5 Testing proportional hazards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.5.1 Constructed variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.5.2 Score tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.5.3 Computational details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
1
4 Accelerated Failure Time models 75
4.1 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.2 Strata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.3 Penalized models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.4 Specifying a distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.5 Residuals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.5.1 Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.5.2 Deviance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.5.3 Dfbeta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.5.4 Working . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.5.5 Likelihood displacement residuals . . . . . . . . . . . . . . . . . . . . . . . 80
4.6 Predicted values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.6.1 Linear predictor and response . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.6.2 Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.6.3 Quantiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.7 Fitting the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
4.8 Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.9 Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.9.1 Gaussian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.9.2 Extreme value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.9.3 Logistic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.9.4 Other distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6 Multi-state models 93
A Changes from version 2.44 to 3.1 94
A.1 Changes in version 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
A.2 Survt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
A.3 Coxph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
2
Chapter 1
Introduction
1.1 History
Work on the survival package began in 1985 in connection with the analysis of medical research
data, without any realization at the time that the work would become a package. Eventually, the
software was placed on the Statlib repository hosted by Carnegie Mellon University. Multiple
version were released in this fashion but I don't have a list of the dates version 2 was the rst
to make use of the print method that was introduced in `New S' in 1988, which places that
release somewhere in 1989. The library was eventually incorporated directly in S-Plus, and from
there it became a standard part of R.
I suspect that one of the primary reasons for the package's success is that all of the functions
have been written to solve real analysis questions that arose from real data sets; theoretical
issues were explored when necessary but they have never played a leading role. As a statistician
in a major medical center, the central focus of my department is to advance medicine; statistics
is a tool to that end. This also highlights one of the deciencies of the package: if a particular
analysis question has not yet arisen in one of my studies then the survival package will also have
nothing to say on the topic. Luckily, there are many other R packages that build on or extend
the survival package, and anyone working in the eld (the author included) can expect to use
more packages than just this one. I certainly never foresaw that the library would become as
popular as it has.
This vignette is an introduction to version 3.x of the survival package. We can think of
versions 1.x as the S-Plus era and 2.1 2.44 as maturation of the package in R. Version 3 had 4
major goals.
Make multi-state curves and models as easy to use as an ordinary Kaplan-Meier and Cox
model.
3
With over 600 dependent packages in 2019, not counting Bioconductor, other guiding lights
of the change are
Allow other packages to build on this one. That means clear documentation of all of the
results that are produced, the use of simple S3 objects that are easy to manipulate, and
setting up many of the routines as a pair. For example, concordance and concordancefit;
the former is the user front end and the latter does the actual work. Other package authors
might want to access the lower level interface, while accepting the penalty of fewer error
checks.
This meant preserving the current argument names as much as possible. Appendix A.1
summarizes changes that were made which are not backwards compatible.
The two other major changes are to collapse many of vignettes into this single large one, and
the parallel creation of an actual book. Documentation is an ongoing process, and there are still
things the package can do which are not well described. That said, we've recognized that the
package needs more than a vignette. With the book's (eventual) appearance this vignette can
also be more brief, essentially leaving out a lot of the theory.
Version 3 will not appear all at once, however; it will take some time to get all of the
documentation sorted out in the way that we like.
1. Incomplete information. At the time of an analysis, not everyone will have yet had the
event. This is a form of partial information known as censoring : if a particular subject
was enrolled in a study 2 years ago, and has not yet had an event at the time of analysis,
we only know that their time to event is >2 years.
2. Dated results. In order to report 5 year survival, say, from a treatment, patients need to be
enrolled and then followed for 5+ years. By the time recruitment and follow-up is nished,
analysis done, the report nally published the treatment in question might be 8 years old
and considered to be out of date. This leads to a tension between early reporting and long
term outcomes.
Survival data is often represented as a pair (ti , δi ) where t is the time until endpoint or last
follow-up, and δ t and 1 =subject had
is a 0/1 variable with 0= subject was censored at
t, or in R code as Surv(time, status). The status variable can be logical, e.g.,
an event at
vtype=='death' where vtype is a variable in the data set. An alternate view is to think of time
4
Alive Dead 0 1 2 ...
Transplant
Illness
Death
Death
5
to event data as a multi-state process as is shown in gure 1.1. The upper left panel is simple
survival with two states of alive and dead, classic survival analysis. The other three panels
show repeated events of the same type (upper right)
competing risks for subjects on a liver transplant waiting list(lower left) and the illness-death
model (lower right). In this approach interest normally centers on the transition rates or hazards
(arrows) from state to state (box to box). For simple survival the two multistate/hazard and
the time-to-event viewpoints are equivalent, and we will move freely between them, i.e., use
whichever viewpoint is handy at the moment. When there more than one transition the rate
approach is particularly useful.
The gure also displays a 2 by 2 division of survival data sets, one that will be used to
organize other subsections of this document.
1.3 Overview
The summary below is purposefully very terse. If you are familiar with survival analysis and with
other R modeling functions it will provide a good summary. Otherwise, just skim the section to
get an overview of the type of computations available from this package, and move on to section
3 for a fuller description.
Surv() A packaging function; like I() it doesn't transform its argument. This is used for the
left hand side of all the formulas.
6
coxph(y ∼ offset(x1) + x2) force in a known term, without estimating a coef-
cient for it.
cox.zph Computes a test of proportional hazards for the tted Cox model.
survdi One and k-sample versions of the Fleming-Harrington Gρ family. Includes the logrank
and Gehan-Wilcoxon as special cases.
survexp Predicted survival for an age and sex matched cohort of subjects, given a baseline
matrix of known hazard rates for the population. Most often these are US mortality
tables, but we have also used local tables for stroke rates.
Data set creation survSplit break a survival data set into disjoint portions of time
tmerge create survival data sets with time-dependent covariates and/or multiple
events
7
March 10 1990 and followed until an analysis date of June 2000 will have 10 years of potential
follow-up, but someone who recieved the treatment in 1995 will only have 5 years at the analysis
date. Let Yi (t), i = 1, . . . , n be the indicator that subject i is at risk and under observation at
time t. Let Ni (t) be the step function for the ith subject, which counts the number of events
for that subject up to time t. There might me things that can happen multiple times such
as rehospitalization, or something that only happens once such as death. The total number of
P
events that have occurred up to time
P t will be N (t) =
Ni (t), and the number of subjects at
risk at time t will be Y (t) = Yi (t). Time-dependent covariates for a subject are the vector
Xi (t). It will also be useful to dene d(t) as the number of deaths that occur exactly at time t.
8
Chapter 2
Survival curves
resid.ds=1
time n.risk n.event survival std.err lower 95% CI upper 95% CI
0.0 11 0 1.000 0.0000 1.000 1
0.5 11 0 1.000 0.0000 1.000 1
1.0 10 1 0.909 0.0867 0.754 1
1.5 8 0 0.909 0.0867 0.754 1
2.0 6 2 0.682 0.1536 0.438 1
9
resid.ds=2
time n.risk n.event survival std.err lower 95% CI upper 95% CI
0.0 15 0 1.000 0.000 1.000 1.000
0.5 12 3 0.800 0.103 0.621 1.000
1.0 10 3 0.600 0.126 0.397 0.907
1.5 4 3 0.375 0.130 0.190 0.738
2.0 4 0 0.375 0.130 0.190 0.738
The default printout is very brief, only one line per curve, showing the number of observations,
number of events, median survival, and optionally the restricted mean survival time (RMST) in
each of the groups. In the above case we used the value at 2.5 years = 913 days as the upper
threshold for the RMST, the value of 453 for females represents an average survival for 453 of
the next 913 days after enrollment in the study. The summary function gives a more complete
description of the curve, in this case we chose to show the values every 6 months for the rst
two years. In this case the number of events (n.event) column is the number of deaths in the
interval between two time points, all other columns reect the value at the chosen time point.
Arguments for the survt function include the usual data, weights, subset and na.action
arguments common to modeling formulas. A further set of arguments have to do with standard
errors and condence intervals, defaults are shown in parenthesis.
se.t (TRUE): compute a standard error of the estimates. In a few rare circumstances
omitting the standard error can save computation time.
conf.int (.95): the level of condence interval, or FALSE if intervals are not desired.
For the default conf.type the condence intervals are computed as exp[log(p)±1.96se(log(p))]
rather than the direct formula of p±1.96(se)(p), where p = S(t) is the survival probability. Many
authors have investigated the behavior of transformed intervals, and a general conclusion is that
the direct intervals do not behave well, particularly near 0 and 1, while all the others are ac-
ceptable. Which of the choices of log, log-log, or logit is best depends on the details of any
particular simulation study, all are available as options in the function. (The default corresponds
to the most recent paper the author had read, at the time the default was chosen; a current
meta review might give a slight edge to the log-log option.)
The conf.lower option is mostly used for graphs. If a study has a long string of censored
observations, it is intuitive that the precision of the estimated survival must be decreasing due
to a smaller sample size, but the formal standard error will not change until the next death.
This option widens the condence interval between death times, proportional to the number at
risk, giving a visual clue of the decrease in n. There is only a small (and decreasing) population
of users who make use of this.
The most common use of survival curves is to plot them, as shown below.
10
> plot(fit1, col=1:2, xscale=365.25, lwd=2, mark.time=TRUE,
xlab="Years since study entry", ylab="Survival")
> legend(750, .9, c("No residual disease", "Residual disease"),
col=1:2, lwd=2, bty='n')
1.0
No residual disease
0.8
Residual disease
0.6
Survival
0.4
0.2
0.0
xaxs('r') It has been traditional to have survival curves touch the left axis (I will not
speculate as to why). This can be accomplished using xaxs='S', which was the default
before survival 3.x. The current default is the standard R style, which leaves space between
the curve and the axis.
The follow-up time in the data set is in days. This is very common in survival data, since it
is often generated by subtracting two dates. The xscale argument has been used to convert
to years. Equivalently one could have used Surv(futime/365.25, status) in the original
11
call to convert all output to years. The use of scale in print and summary and xscale in
plot is a historical mistake.
Subjects who were not followed to death are censored at the time of last contact. These
appear as + marks on the curve. Use the mark.time option to suppress or change the
symbol.
By default pointwise 95% condence curves will be shown if the plot contains a single
curve; they are by default not shown if the plot contains 2 or more groups.
Condence intervals are normally created as part of the survfit call. However, they can
be omitted at that point, and added later by the plot routine.
1:Restricted in physically strenuous activity but ambulatory and able to carry out work of
a light or sedentary nature, e.g., light house work, oce work
2: Ambulatory and capable of all selfcare but unable to carry out any work activities. Up
and about more than 50% of waking hours
3: Capable of only limited selfcare, conned to bed or chair more than 50% of waking
hours
4: Completely disabled. Cannot carry on any selfcare. Totally conned to bed or chair
12
> plot(fit2[1:3], lty=1:3, lwd=2, xscale=365.25, fun='event',
xlab="Years after enrollment", ylab="Survival")
> legend(550, .6, paste("Performance Score", 0:2, sep=' ='),
lty=1:3, lwd=2, bty='n')
> text(400, .95, "Males", cex=2)
1.0
Males
0.8
0.6
Survival
Performance Score =0
Performance Score =1
Performance Score =2
0.4
0.2
0.0
Mean and median For the Kaplan-Meier estimate, the estimated mean survival is undened
if the last observation is censored. One solution, used here, is to redene the estimate to be zero
beyond the last observation. This gives an estimated mean that is biased towards zero, but there
are no compelling alternatives that do better. With this denition, the mean is estimated as
Z T
µ̂ = Ŝ(t)dt
0
where Ŝ is the Kaplan-Meier estimate and T is the maximum observed follow-up time in the
study. The variance of the mean is
!2
Z T Z T
dN (t)
var(µ̂) = Ŝ(u)du
0 t Y (t)(Y (t) − N (t))
13
P P
where N̄ = Ni is the total counting process and Ȳ = Yi is the number at risk.
The sample median is dened as the rst time at which Ŝ(t) ≤ .5. Upper and lower con-
dence intervals for the median are dened in terms of the condence intervals for S : the upper
condence interval is the rst time at which the upper condence interval for Ŝ is ≤ .5. This
corresponds to drawing a horizontal line at 0.5 on the graph of the survival curve, and using
intersections of this line with the curve and its upper and lower condence bands. In the very
rare circumstance that the survival curve has a horizontal portion at exactly 0.5 (e.g., an even
number of subjects and no censoring before the median) then the average time of that horizonal
segment is used. This agrees with usual denition of the median for even n in uncensored data.
14
Call:
survcheck(formula = Surv(time1, time2, status) ~ 1, data = vdata,
id = id)
Transitions table:
to
from 1 (censored)
(s0) 24 17
1 24 24
Creation of (start time, end time) intervals is a common data manipulation task when there
are multiple events per subject. A later chapter will discuss the tmerge function, which is very
often useful for this task. The survcheck function can be used as check for some of more common
errors that arise in creation; it also will be covered in more detail in a later section. (The output
will be also be less cryptic for later cases, where the states have been labeled.) In the above
data, the engines could only participate in 2 kinds of transitions: from an unnamed initial state
to a repair, (s0) → 1, or from one repair to another one, 1 → 1, or reach end of follow-up. The
second table printed by survcheck tells us that 17 engines had 0 transitions to state 1, i.e., no
valve repairs before the end of observation for that engine, 9 had 1 repair, etc. Perhaps the most
important message is that there were no warnings about suspicious data.
We can now compute the survival estimate. When there are multiple observations per subject
the id statement is necessary. (It is a good idea any time there could be multiples, even if there
are none, as it lets the underlying routines check for doubles.)
15
2.0
Cumulative hazard
1.5
1.0
0.5
0.0
Days
By default, the survfit routine computes both the survival and the Nelson cumulative
hazard estimate
n Z t
X dNi (s)
Λ̂(t) =
i−1 0 Y (s)
Like the KM, the Nelson estimate is a step function, it starts at zero and has a step of size
d(t)/Y (t) at each death. To plot the cumulative hazard the cumhaz argument of survfit is
used. In multi-event data, the cumulative hazard is an estimate of the expected number of
events for a unit that has been observed for the given amount of time, whereas the survival
S estimates the probability that a unit has had 0 repairs. The cumulative hazard is the more
natural quantity to plot in such studies; in reliability analysis it is also known as the mean
cumulative function.
The estimate is also important in multi-state models. An example is the occurene of repeated
infections in children with chronic granultomous disease, as found in the cgd data set.
16
2.0
1.5
Cumulative hazard
1.0
0.5
0.0
Here is a simple competing risks example where the three endpoints are labeled as a, b and c.
17
states
4
> summary(tfit)
Call: survfit(formula = Surv(time, endpoint) ~ 1, data = crdata, id = id,
istate = istate)
The resulting object tfit contains an estimate of P (state), the probability of being in each state
at each time t. P is a matrix with one row for each time and one column for each of the four
states ac and still in the starting state. By denition each row of P sums to 1. We will also
use the notation p(t) where p is a vector with one element per state and pj (t) is the fraction in
state j at time t. The plot below shows all 4 curves. (Since they sum to 1 one of the 4 curves is
redundant, often the entry state is omitted since it is the least interesting.) In theplot.survfit
function there is the argument noplot="(s0)" which indicates that curves for state (s0) will not
be plotted. If we had not specied istate in the call to survfit, the default label for the initial
state would have been s0 and t he solid curve would not have been plotted.
18
1.0
0.8
Probability in state
0.6
0.4
0.2
0.0
0 2 4 6 8
The resulting survfms object appears as a matrix and can be subscripted as such, with a
column for each state and rows for each group, each unique combination of values on the right
hand side of the formula is a group or strata. This makes it simple to display a subset of the
curves using plot or lines commands. The entry state in the above t, for instance, can be
displayed with plot(tfit[,1]).
> dim(tfit)
states
4
> tfit$states
[1] "entry" "a" "b" "c"
The curves are computed using the Aalen-Johansen estimator. This is an important concept,
and so we work it out below.
1. The starting point is the column vector p(0) = (1, 0, 0, 0), everyone starts in the rst state.
2. At time 1, the rst event time, form the 4 by 4 transition matrix T1
10/11 1/11 0/11 0/11
0 1 0 0
T (1) = p(1) = p(0)T1
0 0 1 0
0 0 0 1
The rst row of T (1) describes the disposition of everyone who is in state 1 and under
observation at time 1: 10/11 stay in state 1 and 1 subject transitions to state a. There is no
19
one in the other 3 states, so rows 24 are technically undened; use a default stay in the same
state row which has 1 on the diagonal. (Since no one ever leaves states a, b, or c, the bottom
three rows of T will continue to have this form.)
3. At time 2 the rst row will be (9/10, 0, 1/10, 0), and p(2) = p(1)T (2) = p(0)T (1)T (2).
Continue this until the last event time. At a time point with only censoring, such as time 4,
T would be the identity matrix.
It is straightforward to show that when there are only two states of alive -> dead, then p1 (t)
replicates the Kaplan-Meier computation. For competing risks data such as the simple example
above, p(t) replicates the cumulative incidence (CI) estimator. That is, both the KM and CI are
both special cases of the Aalen-Johansen. The AJ is more general, however; a given subject can
have multiple transitions from state to state, including transitions to a state that was visited
earlier.
The mgus2 data set contains information of 1384 subjects who were who were found to have a
particular pattern on a laboratory test (monoclonal gammopathy of undetermined signicance
or MGUS). The genesis of the study was a suspicion that such a result might indicate a predis-
position to plasma cell malignancies such a multiple myeloma; subjects were followed forward to
assess whether an excess did occur. The mean age at diagnosis is 63 years, so death from other
causes will be an important competing risk. Here are a few observations of the data set, one of
which experienced progression to a plasma cell malignancy.
To generate competing risk curves create a new (etime, event) pair. Since each subject has
at most 1 transition, we do not need a multi-line (time1, time2) dataset.
n nevent rmean*
sex=F, (s0) 631 0 139.01247
sex=M, (s0) 753 0 122.97693
sex=F, pcm 631 59 42.77078
sex=M, pcm 753 56 31.82962
20
sex=F, death 631 370 242.21675
sex=M, death 753 490 269.19344
*restricted mean time in state (max time = 424 )
> plot(crfit, col=1:2, noplot="",
lty=c(3,3,2,2,1,1), lwd=2, xscale=12,
xlab="Years post diagnosis", ylab="P(state)")
> legend(240, .65, c("Female, death", "Male, death", "malignancy", "(s0)"),
lty=c(1,1,2,3), col=c(1,2,1,1), bty='n', lwd=2)
1.0
0.8
0.6
Female, death
P(state)
Male, death
malignancy
(s0)
0.4
0.2
0.0
0 5 10 15 20 25 30 35
21
> legend(0, .25, c("Males, PCM, incorrect curve", "Males, PCM, competing risk"),
col=1, lwd=2, lty=c(1,2), bty='n')
0.25
0.15
0.10
0.05
0.00
0 5 10 15 20 25 30 35
> dim(crfit)
22
strata states
2 3
> crfit$strata
sex=F sex=M
227 227
> crfit$states
[1] "(s0)" "pcm" "death"
One surprising aspect of multi-state data is that hazards can be estimated independently
although probabilities cannot. If you look at the cumulative hazard estimate from the pcmbad
t above using, for instance, plot(pcmbac, cumhaz=TRUE) you will nd that it is identical to
the cumulative hazard estimate from the joint t. This will arise again with Cox models.
An identier variable is needed to indicate which rows of the dataframe belong to each
subject. If the id argument is missing, the code assumes that each row of data is a
separate subject, which leads to a nonsense estimate when there are actually multiple rows
per subject.
Subjects do not have to enter at time 0 or all at the same time, but each must traverse a
connected segment of time. Disjoint intervals such as the pair (0, 5], (8, 10] are illegal.
A subject cannot change groups. Any covariates on the right hand side of the formula
must remain constant within subject. (This function is not a way to create supposed
`time-dependent' survival curves.)
Subjects may have case weights, and these weights may change over time for a subject.
The istate argument can be used to designate a subject's state at the start of each t1 , t2
time interval. Like variables in the formula, it is searched for in the data argument. If it is
not present, every subject is assumed to start in a common entry state which is given the name
(s0). The parentheses are an echo of (Intercept) in a linear model and show a label that was
provided by the program rather than the data. The distribution of states just prior to the rst
event time is treated as the initial distribution of states. In common with ordinary survival, any
observation which is censored before the rst event time has no impact on the results.
23
2.4.1 Myeloid data
The myeloid data set contains data from a clinical trial in subjects with acute myeloid leukemia.
To protect patient condentiality the data set in the survival package has been slightly perturbed,
but results are essentially unchanged. In this comparison of two conditioning regimens, the
canonical path for a subject is initial therapy → complete response (CR) → hematologic stem
cell transplant (SCT) → sustained remission, followed by relapse or death. Not everyone follows
this ideal path, of course.
> myeloid[1:5,]
id trt sex futime death txtime crtime rltime
1 1 B f 235 1 NA 44 113
2 2 A m 286 1 200 NA NA
3 3 A f 1983 0 NA 38 NA
4 4 B f 2137 0 245 25 NA
5 5 B f 326 1 112 56 200
The rst few rows of data are shown above. The data set contains the follow-up time and status
at last follow-up for each subject, along with the time to transplant (txtime), complete response
(crtime) or relapse after CR (rltime). Subject 1 did not receive a transplant, as shown by the
NA value, and subject 2 did not achieve CR.
Overall survival curves for the data are shown in gure 2.1. The dierence between the
treatment arms A and B is substantial. A goal of this analysis is to better understand this
dierence. Code to generate the two curves is below.
The full multi-state data set can be created with the tmerge routine.
Our check shows that there is one subject who had CR and stem cell transplant on the same
day (temp=3). To avoid length 0 intervals, we break the tie so that complete response (CR)
happens rst. (Students may be surprised to see anomalies like this, since they never appear in
textbook data sets. In real data such issues always appear.)
24
1.0
0.8
0.6
Survival
0.4
Arm A
Arm B
0.2
0.0
0 1 2 3 4 5 6
25
> tdata <- myeloid # temporary working copy
> tied <- with(tdata, (!is.na(crtime) & !is.na(txtime) & crtime==txtime))
> tdata$crtime[tied] <- tdata$crtime[tied] -1
> mdata <- tmerge(tdata[,1:2], tdata, id=id, death= event(futime, death),
sct = event(txtime), cr = event(crtime),
relapse = event(rltime),
priorcr = tdc(crtime), priortx = tdc(txtime))
> temp <- with(mdata, cr + 2*sct + 4*relapse + 8*death)
> table(temp)
temp
0 1 2 4 8
325 454 364 226 320
> mdata$event <- factor(temp, c(0,1,2,4,8),
c("none", "CR", "SCT", "relapse", "death"))
> mdata[1:7, c("id", "trt", "tstart", "tstop", "event", "priorcr", "priortx")]
id trt tstart tstop event priorcr priortx
1 1 B 0 44 CR 0 0
2 1 B 44 113 relapse 1 0
3 1 B 113 235 death 1 0
4 2 A 0 200 SCT 0 0
5 2 A 200 286 death 0 1
6 3 A 0 38 CR 0 0
7 3 A 38 1983 none 1 0
Subject 1 has a CR on day 44, relapse on day 113, death on day 235 and did not receive a
stem cell transplant. The data for the rst three subjects looks good. Check it out a little more
thoroughly using survcheck.
Transitions table:
to
from CR SCT relapse death (censored)
(s0) 443 106 13 55 29
CR 0 159 168 17 110
SCT 11 0 45 149 158
relapse 0 99 0 99 28
death 0 0 0 0 0
26
count
state 0 1 2 3 4
CR 192 454 0 0 0
SCT 282 364 0 0 0
relapse 420 226 0 0 0
death 326 320 0 0 0
(any) 29 201 174 153 89
The second table shows that no single subject had more than one CR, SCT, relapse, or death;
the intention of the study was to count only the rst of each of these, so this is as expected.
Several subjects visited all four intermediate states. The transitions table shows 11 subjects
who achieved CR after stem cell transplant and another 106 who received a transplant before
achieving CR, both of which are deviations from the ideal pathway. No subjects went from
death to another state (which is good).
For investigating the data we would like to add a set of alternate endpoints.
1. The competing risk of CR and death, ignoring other states. This is used to estimate the
fraction who ever achieved a complete response.
3. An endpoint that distinguishes death after SCT from death before SCT.
Each of these can be accomplished by adding further outcome variables to the data set, we do
not need to change the time intervals.
> levels(mdata$event)
[1] "none" "CR" "SCT" "relapse" "death"
> temp1 <- with(mdata, ifelse(priorcr, 0, c(0,1,0,0,2)[event]))
> mdata$crstat <- factor(temp1, 0:2, c("none", "CR", "death"))
> temp2 <- with(mdata, ifelse(priortx, 0, c(0,0,1,0,2)[event]))
> mdata$txstat <- factor(temp2, 0:2, c("censor", "SCT", "death"))
> temp3 <- with(mdata, c(0,0,1,0,2)[event] + priortx)
> mdata$tx2 <- factor(temp3, 0:3,
c("censor", "SCT", "death w/o SCT", "death after SCT"))
Notice the use of the priorcr variable in dening crstat. This outcome variable treats
complete response as a terminal state, which in turn means that no further transitions are
allowed after reaching CR.
This data set is the basis for our rst set of curves, which are shown in gure 2.2. The plot
overlays three separate survfit calls: standard survival until death, complete response with
death as a competing risk, and transplant with death as a competing risk. For each t we have
shown one selected state: the fraction who have died, fraction ever in CR, and fraction ever
to receive transplant, respectively. Most of the CR events happen before 2 months (the green
vertical line) and nearly all the additional CRs conferred by treatment B occur between months
2 and 8. Most transplants happen after 2 months, which is consistent with the clinical guide of
transplant after CR. The survival advantage for treatment B begins between 4 and 6 months,
which argues that it could be at least partially a consequence of the additional CR events.
The code to draw gure 2.2 is below. It can be separated into 5 parts:
27
CR
Entry
Death
0.6
Fraction with the endpoint
Tx
0.4
Entry
Death
A CR
B CR
0.2
A transplant
B transplant
A death
B death
Entry Death
0.0
0 6 12 24 36 48
Figure 2.2: Overall survival curves: time to death, to transplant (Tx), and to complete response
(CR). Each shows the estimated fraction of subjects who have ever reached the given state. The
vertical line at 2 months is for reference. The curves were limited to the rst 48 months to more
clearly show early events. The right hand panel shows the state-space model for each pair of
curves.
28
1. Fits for the 3 endpoints are simple and found in the rst set of lines. The crstat and
txstat variables are factors, which causes multi-state curves to be generated.
2. The layout and par commands are used to create a multi-part plot with curves on the left
and state space diagrams on the right, and to reduce the amount of white space between
them.
3. Draw a subset of the curves via subscripting. A multi-state survt object appears to the
user as a matrix of curves, with one row for each group (treatment) and one column for
each state. The CR state is the second column in sfit2, for instance. The CR t was
drawn rst simply because it has the greatest y-axis range, then the other curves added
using the lines command.
4. Decoration of the plots. This includes the line types, colors, legend, choice of x-axis labels,
etc.
5. Add the state space diagrams. The functions for this are described elsewhere in the vi-
gnette.
29
0.7
Entry transplant
0.6
0.5
0.4
transplant
P(state)
Entry
0.3
Death
Arm A
Arm B
0.2
0.1
0.0
0 6 12 24 36 48
Figure 2.3: Correct (solid) and invalid (dashed) estimates of the number of subjects transplanted.
> par(mar=c(4,.1,1,1))
> crisk(c("Entry", "CR", "Death"), alty=3)
> crisk(c("Entry", "Tx", "Death"), alty=2)
> crisk(c("Entry","Death"))
> par(oldpar)
> layout(1)
The association between a particular curve and its corresponding state space diagram is
critical. As we will see below, many dierent models are possible and it is easy to get confused.
Attachment of a diagram directly to each curve, as was done above, will not necessarily be day-
to-day practice, but the state space should always be foremost. If nothing else, draw it on a
scrap of paper and tape it to the side of the terminal when creating a data set and plots.
Figure 2.3 shows the transplant curves overlaid with the naive KM that censors subjects at
death. There is no dierence in the initial portion as no deaths have yet intervened, but the
nal portion overstates the transplant outcome by more than 10%.
1. The key problem with the naive estimate is that subjects who die can never have a trans-
plant. The result of censoring them is an estimate of the fraction who would be trans-
planted, if death before transplant were abolished. This is not a real world quantity.
30
2. In order to estimate this ctional quantity one needs to assume that death is uninforma-
tive with respect to future disease progression. The early deaths in months 02, before
transplant begins, are however a very dierent class of patient. Non-informative censoring
is untenable.
We are left with an unreliable estimate of an uninteresting quantity. Mislabeling any true state
as censoring is always a mistake, one that will not be repeated here. Here is the code for gure
2.3. The use of a logical (true/false) as the status variable in the Surv call leads to ordinary
survival calculations.
31
CR
Entry
0.6
Death
0.4
CR
0.2
CR
Entry
Death/Relapse
0.0
0 2 4 6 8 10 12
Months
Figure 2.4: Models for `ever in CR' and `currently in CR'; the only dierence is an additional
transition. Both models ignore transplant.
32
The above code created yet another event variable so as to ignore transitions to the transplant
state. They become a non-event, in the same way that extra lines with a status of zero are used
to create time-dependent covariates for a Cox model t.
The survfit call above included the influence=TRUE argument, which causes the inuence
array to be calculated and returned. It contains, for each subject, that subject's inuence on the
time by state matrix of results and allows for calculation of the standard error of the restricted
mean. We will return to this in a later section.
The restricted mean time in the CR state is extended by 21.2 - 16.3 = 4.89 months. A
question which immediately gets asked is whether this dierence is signicant, to which there
are two answers. The rst and more important is to ask whether 5 months is an important
gain from either a clinical or patient perspective. The overall restricted mean survival for the
study is approximately 30 of the rst 48 months post entry (use print(sfit1, rmean=48)); on
this backdrop an extra 5 months in CR might or might not be an meaningful advantage from
a patient's point of view. The less important answer is to test whether the apparent gain is
suciently rare from a mathematical point of view, i.e., statistical signicance. The standard
errors of the two values are 1.1 and 1.1, and since they are based on disjoint subjects the values
√
are independent, leading to a standard error for the dierence of 1.12 + 1.12 = 1.6. The 5
month dierence is more than 3 standard errors, so highly signicant.
In summary
Arm B adds late complete responses (about 4%); there are 206/317 in arm A vs. 248/329
in arm B.
CR → transplant is the target treatment path for a patient; given the improvements listed
above why does gure 2.2 show no change in the number transplanted? Figure 2.5 shows the
transplants broken down by whether this happened before or after complete response. Most
33
Entry
0.4
Transplant CR
0.3
Transplanted
Transplant
0.2
A, transplant without CR
0.1
B, transplant without CR
A, transplant after CR
B, transplant after CR
0.0
0 6 12 24 36 48
Months
Figure 2.5: Transplant status of the subjects, broken down by whether it occurred before or
after CR.
34
of the non-CR transplants happen by 10 months. One possible explanation is that once it is
apparent to the patient/physician pair that CR is not going to occur, they proceed forward with
other treatment options. The extra CR events on arm B, which occur between 2 and 8 months,
lead to a consequent increase in transplant as well, but at a later time of 1224 months: for a
subject in CR we can perhaps aord to defer the transplant date.
Computation is again based on a manipulation of the event variable: in this case dividing the
transplant state into two sub-states based on the presence of a prior CR. The code makes use
of the time-dependent covariate priorcr. (Because of scheduling constraints within a hospital
it is unlikely that a CR that is within a few days prior to transplant could have aected the
decision to schedule a transplant, however. An alternate breakdown that might be useful would
be transplant without CR or within 7 days after CR versus those that are more than a week
later. There are many sensible questions that can be asked.)
35
0.7
0.6
Entry
0.5
Death
Current state
0.4
CR Tx Rel
Transplant
0.3
0.2
CR
0.1
Death
0.0
Recurrence
0 6 12 24 36 48
Months
Figure 2.6: The full multi-state curves for the two treatment arms.
36
> sfit4 <- survfit(Surv(tstart, tstop, event) ~ trt, mdata, id=id)
> sfit4$transitions
to
from CR SCT relapse death (censored)
(s0) 443 106 13 55 29
CR 0 159 168 17 110
SCT 11 0 45 149 158
relapse 0 99 0 99 28
death 0 0 0 0 0
> layout(matrix(1:2,1,2), widths=2:1)
> oldpar <- par(mar=c(5.1, 4.1, 1,.1))
> plot(sfit4, col=rep(1:4,each=2), lwd=2, lty=1:2, xmax=48, xaxt='n',
xlab="Months", ylab="Current state")
> axis(1, xtime, xtime)
> text(c(40, 40, 40, 40), c(.51, .13, .32, .01),
c("Death", "CR", "Transplant", "Recurrence"), col=c(4,1,2,3))
> par(mar=c(5.1, .1, 1, .1))
> state5()
> par(oldpar)
The transitions table above shows 55 direct transitions from entry to death, i.e., subjects who
die without experiencing any of the other intermediate points, 159 who go from CR to transplant
(as expected), 11 who go from transplant to CR, etc. No one was observed to go from relapse
to CR in the data set, this serves as a data check since it should not be possible per the data
entry plan.
where Dij (t) is the inuence of subject i on pj (t), and pj (t) is the estimated probability for state
j at timet. This is known as the innitesimal jackknife (among other labels).
> crsurv <- survfit(Surv(tstart, tstop, cr2) ~ trt,
data= mdata, id=id, influence=TRUE)
> curveA <- crsurv[1,] # select treatment A
> dim(curveA) # P matrix for treatement A
strata states
1 5
> curveA$states
[1] "(s0)" "CR" "SCT" "relapse" "death"
37
> dim(curveA$pstate) # 426 time points, 5 states
[1] 426 5
> dim(curveA$influence) # influence matrix for treatment A
[1] 317 426 5
> table(myeloid$trt)
A B
317 329
For treatment arm A there are 317 subjects and 426 time points in the P matrix. The
inuence array has subject as the rst dimension, and for each subject it has an image of the
P matrix containing that subject's inuence on each value in P, i.e., influence[1, ,] is the
inuence of subject 1 on P. For this data set everyone starts in the entry state, so p(0) = the
rst row of pstate will be (1, 0, 0, 0, 0) and the inuence of each subject on this row is 0; this
does not hold if not all subjects start in the same state.
As an exercise we will calculate the mean time in state out to 48 weeks. This is the area
under the individual curves from time 0 to 48. Since the curves are step functions this is simple
sum of rectangles, treating any intervals after 48 months as having 0 width.
The last lines verify that this is exactly the calculation done by the print.survfitms func-
tion; the results can also be found in the table component returned by summary.survfitms.
38
Ui be the inuence of subject i. For some function f (P ) of the probability
In general, let
in state matrix pstate, the inuence of subject i P will be δi = f (P + Ui ) − f (P ) and the
2
innitesimal jackknife estimate of variance will be i δ . For the simple case of adding up
rectangles f (P + Ui ) − f (P ) = f (Ui ) leading to particularly simple code, but this will not always
be the case.
39
incorrect, but the model based variance would have the same assumption so it is a choice between
two evils. Responsibility falls on the user to clarify the proper clustering. (A error or warning
from the code would be defensible, but the package author so dislikes packages that chatter
warnings all the time that he is loath to do so.)
The innitesimal jackknife (IJ) matrix contains the inuence of each subject on the estimator;
formally the derivative with respect to each subject's case weight. For a single simple survival
curve that has k unique values, for instance, the IJ matrix will have n rows and k columns,
one row per subject. Columns of the matrix sum to zero, by denition, and the variance at a
time point t (IJ)2 . For a competing risk problem the crfit object
will be the column sums of
above will contain a matrix pstate with k rows and one column for each state, where k is the
number of unique time points; and the IJ is an array of dimension (n, k, p). In the case of simple
survival and all case weights =1, the IJ variance collapses to the well known Greenwood variance
estimate.
1. A layout vector or matrix. A vector with values of (1, 3, 1) for instance will allocate one
state, then a column with 3 states, then one more state, proceeding from left to right. A
matrix with a single row will do the same, whereas a matrix with one column will proceed
from top to bottom.
The rst few state space diagrams were competing risk models, which use the following helper
function. It accepts a vector of state names, where the rst name is the starting state and the
remainder are the possible outcomes.
40
connect <- matrix(c(0,0,0, 1,0,0, 1,1,0), 3,3,
dimnames=list(what, what))
if (horizontal) statefig(1:2, connect, ...)
else statefig(matrix(1:2, ncol=1), connect, ...)
}
The most complex of the state space gures has all 5 states.
The Aalen-Johansen method used by survfit does not account for interval censoring, also
known as panel data, where a subject's current state is recorded at some xed time such as
a medical center visit but the actual times of transitions are unknown. Such data requires
further assumptions about the transition process in order to model the outcomes and has a more
complex likelihood. The msm package, for instance, deals with data of this type. If subjects
reliably come in at regular intervals then the dierence between the two results can be small,
e.g., the msm routine estimates time until progression occurred whereas survfit estimates time
until progression was observed.
41
When using multi-state data to create Aalen-Johansen estimates, individuals are not al-
lowed to have gaps in the middle of their time line. An example of this would be a data
set with (0, 30, pcm] and (50,70, death] as the two observations for a subject where the
time from 30-70 is not accounted for.
Subjects must stay in the same group over their entire observation time, i.e., variables on
the right hand side of the equation cannot be time-dependent.
A transition to the same state is allowed, e.g., observations of (0,50, 1], (50, 75, 3], (75,
89, 4], (89, 93, 4] and (93, 100, 4] for a subject who goes from entry to state 1, then to
state 3, and nally to state 4. However, a warning message is issued for the data set in
this case, since stuttering may instead be the result of a coding mistake. The same result
is obtained if the last three observations were collapsed to a single row of (75, 100, 4].
42
Chapter 3
Cox model
The most commonly used models for survival data are those that model the transition rate
from state to state, i.e., the arrows of gure 1.1. They are Poisson regression (3.1), the Cox or
proportional hazards model (3.2) and the Aalen additive regression model (3.3), of which the
Cox model is far and away the most popular. As seen in the equations they are closely related.
(Textbooks on survival use λ(t), α(t) and h(t) in about equal proportions. There is no good
argument for any one versus another, but this author started his career with books that used λ
so that is what you will get.)
43
Likelihood ratio test=14.7 on 3 df, p=0.00212
n= 214, number of events= 152
(14 observations deleted due to missingness)
> summary(cfit1, digits=3)
Call:
coxph(formula = Surv(time, status) ~ age + sex + wt.loss, data = lung)
As is usual with R modeling functions, the default print routine gives a short summary and
the summary routine a longer one. The anova command shows tests for each term in a model,
added sequentially. We purposely avoid the innane addition of signicant stars to any printout.
Age and gender are strong predictors of survival, but the amount of recent weight loss was not
inuential.
The following functions can be used to extract portions of a coxph object.
44
fitted: the tted values, also known as linear predictors
Further details about the contents of a coxph object can be found by help('coxph.object').
The global na.action function has an important eect on the returned vector of residuals, as
shown below. This can be set per t, but is more often set globally via the options() function.
The ts have excluded 14 subjects with missing values for one or more covariates. The residual
vector r1 omits those subjects from the residuals, while r2 returns a vector of the same length
as the original data, containing NA for the omitted subjects. Which is preferred depends on
what you want to do with the residuals. For instance mean(r1) is simpler using the rst while
plot(lung$ph.ecog, r2) is simpler with the second.
Stratied Cox models are obtained by adding one or more strata terms to the model formula.
In a stratied model each subject is compared only to subjects within their own stratum for
computing the partial likelihood, and then the nal results are summed over the strata. A useful
rule of thumb is that a variable included as a stratum is adjusted for in the most general way,
at the price of not having an estimate of its eect. One common use of strata is to adjust for
the enrolling institution in a multi-center study, as below. We see that in this case the eect of
stratication is slight.
45
simple stratified
age 0.0201 0.0235
sex -0.5210 -0.5160
wt.loss 0.0008 -0.0017
Predicted survival curves from a Cox model are obtained using the survfit function. Since
these are predictions from a model, it is necessary to specify whom the predictions should be
for, i.e., one or more sets of covariate values. Here is an example.
46
1.0
0.8
0.6
Survival
0.4
0.2
0.0
Years
The simplifying aspects of the Cox model that make is so useful are exactly those that should
be veried, namely proportional hazards, additivity, linearity, and lack of any high leverage
points. The rst can be checked with the cox.zph function.
47
1.5
1.0
0.5
Beta(t) for sex
0.0
−0.5
−1.0
−1.5
−2.0
Time
None of the test statistics for PH are remarkable. A simple check for linearity of age is to
replace the term with a smoothing spline.
48
> anova(cfit1, cfit4)
Analysis of Deviance Table
Cox model: response is Surv(time, status)
Model 1: ~ age + sex + wt.loss
Model 2: ~ age + sex + wt.loss + age:sex
loglik Chisq Df Pr(>|Chi|)
1 -673.06
2 -672.88 0.3473 1 0.5557
2
1
Partial for pspline(age)
0
−1
−2
40 50 60 70 80
age
The age eect appears reasonbly linear. Additivity can be examined by adding an age by sex
interaction, and again is not remarkable.
49
dierent type of subject. Adding the hospital category as a strata allows each group to have a
dierent shape of baseline hazard.
Further examination shows that the t is problematic in that only 3 of 128 children have
steroids ==1, so we ret without that variable.
Predicted survival and/or cumulative hazard curves can then be obtained from the tted
model. Prediction requires the user to speciy who to predict; in this case we will use 4 hypo-
thetical subjects on control/interferon treatment, at ages 7 and 20 (near the quantiles). This
creates a data frame with 4 rows.
50
2 12 X-linked placebo
3 6 X-linked rIFN-g
4 12 X-linked rIFN-g
> csurv <- survfit(cfit2, newdata=dummy)
> dim(csurv)
strata data
4 4
> plot(csurv[1,], fun="event", col=1:2, lty=c(1,1,2,2),
xlab="Days on study", ylab="Pr( any infection )")
0.8
0.6
Pr( any infection )
0.4
0.2
0.0
Days on study
The resulting object was subscripted in order to make a plot with fewer curves, i.e., predictions
for the rst level of hosp.cat. We see that treatment is eective but the eect of age is small.
Perhaps more interesting in this situation is the expected number of infections, rather than
the probability of having at least 1. The former is estimated by the cumulative hazard, which is
also returned by the survfit routine.
51
1.5
Age 6, control
E( number of infections )
Days on study
3.3.1 MGUS
As an simple multi-state example consider the monoclonal gammopathy data set mgus2, which
contains the time to a plasma cell malignancy (PCM), usually multiple myleoma, and the time
to death for 1384 subjects found to have a condition known as monoclonal gammopathy of un-
determined signicance (MGUS), based on a particular test. This data set has already appeared
in 2.3.2. The time values in the data set are from detection of the condition. Here are a subset
of the observations along with a simple state gure for the data.
> mgus2[56:59,]
id age sex dxyr hgb creat mspike ptime pstat futime death etime
56 56 78 M 1978 10.3 3.0 1.9 29 1 44 1 29
57 57 79 F 1981 13.6 1.3 1.3 84 0 84 1 84
58 58 72 F 1972 13.6 1.2 0.4 321 0 321 1 321
59 59 80 F 1984 10.6 0.9 1.2 147 0 147 1 147
event
52
56 pcm
57 death
58 death
59 death
> sname <- c("MGUS", "Malignancy", "Death")
> smat <- matrix(c(0,0,0, 1,0,0, 1,1,0), 3, 3,
dimnames = list(sname, sname))
> statefig(c(1,2), smat)
Malignancy
MGUS
Death
In this data set subject 56 was diagnosed with a PCM 29 months after detection of MGUS
and died at 44 months. This subject passes through all three states. The other three listed
individuals died without a plasma cell malignancy and traverse one of the arrows; 103 subjects
(not shown) are censored before experiencing either event and spend their entire tenure in the
leftmost state. The competing risks model will ignore the transition from malignacy to death:
the two ending states are malignancy before death and death without malignancy.
The statefig function is designed to create simple state diagrams, with an emphasis on ease
rather than elegance. See more information in section 2.8.
For competing risks each subject has at most one transition, so the data set only needs one
row per subject.
53
> crdata$event <- factor(crdata$event, 0:2, c("censor", "PCM", "death"))
> quantile(crdata$age, na.rm=TRUE)
0% 25% 50% 75% 100%
24 63 72 79 96
> table(crdata$sex)
F M
631 753
> quantile(crdata$mspike, na.rm=TRUE)
0% 25% 50% 75% 100%
0.0 0.6 1.2 1.5 3.0
> cfit <- coxph(Surv(etime, event) ~ I(age/10) + sex + mspike,
id = id, crdata)
> print(cfit, digits=1) # narrow the printout a bit
Call:
coxph(formula = Surv(etime, event) ~ I(age/10) + sex + mspike,
data = crdata, id = id)
54
> dummy <- expand.grid(sex=c("F", "M"), age=c(60, 80), mspike=1.2)
> csurv <- survfit(cfit, newdata=dummy)
> plot(csurv[,2], xmax=20*12, xscale=12,
xlab="Years after MGUS diagnosis", ylab="Pr(has entered PCM state)",
col=1:2, lty=c(1,1,2,2), lwd=2)
> legend(100, .04, outer(c("female,", "male, "),
c("diagnosis at age 60", "diagnosis at age 80"),
paste),
col=1:2, lty=c(1,1,2,2), bty='n', lwd=2)
0.12
0.10
Pr(has entered PCM state)
0.08
0.06
0.04
0 5 10 15 20
55
A single outcome t using only time to progression is instructive: we obtain exactly the same
coecients but dierent absolute risks. This is a basic property of multi-state models: hazards
can be explored separately for each transition, but absolute risk must be computed globally.
(The estimated cumulative hazards from the two models are also identical). The incorrect curve
is a vain attempt to estimate the progression rate which would occur if death could be abolished.
It not surprisingly ends up as about 1% per year.
0 5 10 15 20
56
3.4 Multiple event types and multiple events per subject
Non-alcoholic fatty liver disease (NAFLD) is dened by three criteria: presence of greater than
5% fat in the liver (steatosis), absence of other indications for the steatosis such as excessive
?
alcohol consumption or certain medications, and absence of other liver disease [ ]. NAFLD is
currently responsible for almost 1/3 of liver transplants and it's impact is growing, it is expected
?
to be a major driver of hepatology practice in the coming decade [ ], driven at least in part by
the growing obesity epidemic. The nafld data set includes all patients with a NAFLD diagnosis
in Olmsted County, Minnesota between 1997 to 2014 along with up to four age and sex matched
?
controls for each case [ ].
We will model the onset of three important components of the metabolic syndrome: diabetes,
hypertension, and dyslipidemia, using the model shown below. Subjects have either 0, 1, 2, or
all 3 of these metabolic comorbidities.
death
57
3.4.1 Data
The NAFLD data is represented as 3 data sets, nafld1 has one observation per subject containing
basline information (age, sex, etc.), nad2 has information on repeated laboratory tests, e.g.
blood pressure, and nad3 has information on yes/no endpoints. After the case-control set
was assembled, we removed any subjects with less than 7 days of follow-up. These subjects
add little information, and it prevents a particular confusion that can occur with a multi-day
medical visit where two results from the same encounter have dierent dates. To protect patient
condentiality all time intervals are in days since the index date; none of the dates from the
original data were retained. Subject age is their integer age at the index date, and the subject
identier is an arbitrary integer. As a nal protection, a 10% random sample of subjects was
excluded. As a consequence analyses results will not exactly match the original paper.
Start by building an analysis data set using nafld1 and nafld3.
> ndata <- tmerge(nafld1[,1:8], nafld1, id=id, death= event(futime, status))
> ndata <- tmerge(ndata, subset(nafld3, event=="nafld"), id,
nafld= tdc(days))
> ndata <- tmerge(ndata, subset(nafld3, event=="diabetes"), id = id,
diabetes = tdc(days), e1= cumevent(days))
> ndata <- tmerge(ndata, subset(nafld3, event=="htn"), id = id,
htn = tdc(days), e2 = cumevent(days))
> ndata <- tmerge(ndata, subset(nafld3, event=="dyslipidemia"), id=id,
lipid = tdc(days), e3= cumevent(days))
> ndata <- tmerge(ndata, subset(nafld3, event %in% c("diabetes", "htn",
"dyslipidemia")),
id=id, comorbid= cumevent(days))
> summary(ndata)
Call:
tmerge(data1 = ndata, data2 = subset(nafld3, event %in% c("diabetes",
"htn", "dyslipidemia")), id = id, comorbid = cumevent(days))
58
There are 13 nad splits that fall after the end of follow-up (`late'). These are subjects
whose rst NAFLD fell within a year of the end of their time line, and the one year delay
for conrmed pushed them over the end. (The time value in the nafld3 data set is 1
year after the actual notice of NAFLD; no other endpoints have this oset added). The
time dependent covariate nafld never turns from 0 to 1 for these subjects. (Why were
these subjects not removed earlier by my at least 7 days of follow-up rule? They are all
controls for someone else and so appear in the data at a younger age than their NAFLD
date.)
318 subjects have a NAFLD diagnosis between time 0 and last follow-up. These are subjects
who were selected as matched controls for another NAFLD case at a particular age, and
later were diagnosed with NAFLD themselves.
2393 of the diabetes diagnoses are before entry, i.e., these are the prevalent cases. One
diagnosis occurred on the day of entry (leading), and will not be counted as a post-
enrollment endpoint, all the other fall somewhere between study entry and last follow-up.
Conversely, 5 subjects were diagnosed with hypertension at their nal visit (trailing).
These will be counted as an occurrence of a hypertension event (e2), but the time dependent
covariate htn will never become 1.
575 of the total comorbidity counts are tied. These are subjects for whom the rst diagnosis
of 2 of the 3 conditions happened on the same oce visit, the cumulative count will jump
by 2. (We will see below that 4 subjects had all 3 on the same day.) Many times ties
indicate a data error.
Such a detailed look at data set construction may seem over zealous. Our experience is that
issues with covariate and event timing occur in nearly all data sets, large or small. The 13
NAFLD cases after last follow-up were for instance both a surprise and a puzzle to us; but we
have learned through experience that it is best not to proceed until such puzzles are understood.
(This particular one was benign.) If, for instance, some condition is noted at autopsy, do we
want the related time dependent covariate to change before or after the death event? Some sort
of decision has to be made, and it is better to look and understand than to blindly accept an
arbitrary programming default.
3.4.2 Fits
Create the covariates for current state and the analysis endpoint. It is important that data
manipulations like this occur after the nal tmerge call. Successive tmerge calls keep track of
the time scale, time-dependent and event covariates, passing the information forward from call
to call, but this information is lost when the resulting data frame is manipulated. (The loss is
intentional: we won't know if one of the tracked variables has changed.)
The tmerge call above used the cumevent verb to count comorbidities, and the rst line
below veries that no subject had diabetes, for instance, coded more than once. For this analysis
we think of the three conditions as one-time outcomes, you can't get diabetes twice. When the
outcome data set is the result of electronic capture one could easily have a diabetes code at every
visit, in which case the cumulative count of all events would not be the total number of distinct
comorbidities. In this particular data set the diabetes codes had already been preprocessed so
59
that the data set contains only the rst diabetes diagnosis, and likewise with hypertension and
dyslipidemia. (In counterpoint, the nad3 data set has multiple myocardial infarctions for some
subjects, since MI can happen more than once.)
Transitions table:
to
from 1mc 2mc 3mc death (censored)
0mc 1829 70 4 263 5705
1mc 0 1843 28 243 4567
2mc 0 0 1048 417 3687
3mc 0 0 0 441 2220
death 0 0 0 0 0
This is a rich data set with a large number of transitions: over 1/4 of the participants have
at least one event, and there are 22 subjects who transition through all 5 possible states (4
transitions). Unlike prior examples, subjects do not all enter the study in the same state; about
14% have diabetes at the time of recruitment, for instance. Note one major dierence between
current state and outcome, namely that the current state endures across intervals: it is based on
tdc variables while the outcome is based on event operators. If a subject has time-dependent
60
covariates, there may be intermediate intervals where a covariate changed but an outcome did not
occur; current state will endure across intervals but the intermediate outcome will be censor.
We see a number of subjects who jump states, e.g., directly from 0 to 2 comorbidities. This
serves to remind us that this is actually a model of time until detected comorbidity; which will
often have such jumps even if the underlying biology is continuous. The data look like the gure
below, where the dotted lines are transformations that we observe, but would not be present if
the subjects were monitored continuously. A call to the survcheck routine is almost mandatory
for a complex setup like this, to ensure that the data set which has been built is what you
intended to build.
Calling survcheck with ~1 on the right hand side or with the covariates for the model on
the right hand side will potentially give dierent event counts, due to the removal of rows with
a missing value. Both can be useful summaries. For a multi-state coxph model neither may
be exactly correct, however. If the model contains a covariate which applies only to certain
transitions, then events that do not depend on that covariate will be retained, while event
occurences that do depend on the covariate will be dropped, leading to counts that may be
intermediate between the two survcheck outputs.
61
No comorbidity
1 comorbidity
Death
2 comorbidities
3 comorbitities
Since age is the dominant driver of the transitions we have chosen to do the ts directly on
age scale rather than model the age eect. We force common coecients for the transitions from
0 comorbidities to 1, 2 or 3, and for transitions from 1 comorbidity to 2 or 3. This is essentially
a model of any progression from a given state. We also force the eect of male sex to be the
same for any transition to death.
A list has been used as the formula for the coxph call. The rst element is a standard formula,
and will be the default for all of the transitions found in the model. Elements 24 of the list are
pseudo formulas, which specify a set of states on the left and covariates on the right, along with
the optional modier /common. As shown, there are multiple ways to specify a set of transitions
62
either by name or by number, the value 0 is shorthand for any state. The coecient matrix
reveals that the 1:2, 1:3, and 1:4 transitions all share the same coecients, as intended.
The actual coecient vector (coef(fit)) and variance covariance matrix do not have repeats.
The t also includes a cmap component that records the mapping between the coecient vector
and the state transtitions. The result of coef(nfit1) is a vector of length 9, the rst element
of which is the nad eect for transitions 1:2, 1:3, and 1:4, the second coecient is the eect of
male on those three transitions, etc. Because the coecient vector, variance matrix, and etc. are
identical to those for a simple coxph call, downstream operations such as predict and summary
are unchanged.
The standard printouts makes use of cmap to rearrange the output into a nicer format. It is
interesting, though not surprising, that the impact of NAFLD on death is largest for those with
0mc and smallest for those with 3mc.
63
1:5 coef exp(coef) se(coef) robust se z p
nafld 0.62990 1.87742 0.22590 0.22793 2.764 0.00572
male 0.32935 1.39006 0.05488 0.05466 6.026 1.69e-09
64
male_1:5 0.32935 1.39006 0.05488 0.05466 6.026 1.69e-09
nafld_2:5 0.53433 1.70630 0.15483 0.14971 3.569 0.000358
nafld_3:5 0.55116 1.73526 0.10585 0.10695 5.153 2.56e-07
nafld_4:5 0.07225 1.07492 0.09929 0.09908 0.729 0.465891
The names attached to the coecients in a multi-state model are a compromise, designed
to give some information to the reader, albeit imperfect. If a variable such as 'sex' only applies
to a single coecient, the simple name is used, even if the coecient corresponds to multiple
transitions. Otherwise a sux _a:b is appended where a:b corresponds to the rst transition
that maps onto this coecient. (First in the sense of standard R matrices, i.e., reading the
elements of cmap in column order.)
A second available keyword is shared, which indicates that the baseline hazards for transi-
tions share a common shape. Here is an example:
65
3.4.3 Timeline data
The survfit and coxph routines also accept data in what we refer to as a timeline form. (The
option is still under development so detail may change.) Timeline data contains a case identier
and a timeline variable, where this value pair that is unique for each row. The other covariates
are any number of variables whose value is what was observed at that time, or missing if there
was no observation of that variable at that time. In contrast to counting process data, there are
no time intervals and no distinction between covariates and endpoints. In this sense the data is
much more straightforward; a simple description of what was seen.
Here is a simple example using the mgus2 data set for a competing risks analysis. The Surv2
operation on the left-hand side indicates to the routine that timeline data is being used.
The counting process data set from tmerge as fewer rows but a more complex structure.
> mdata1[1:3,]
id age sex dxyr hgb creat mspike tstart tstop state
1 1 88 F 1981 13.1 1.3 0.5 0 30 death
2 2 78 F 1968 11.5 1.2 2.0 0 25 death
3 3 94 M 1980 10.5 1.5 2.6 0 46 death
> print(mdata2[1:6,], na.print='.')
id days age sex dxyr hgb creat mspike cstat
1 1 0 88 F 1981 13.1 1.3 0.5 .
2 1 30 NA . NA NA NA NA death
3 2 0 78 F 1968 11.5 1.2 2.0 .
4 2 25 NA . NA NA NA NA death
5 3 0 94 M 1980 10.5 1.5 2.6 .
6 3 46 NA . NA NA NA NA death
Here is a reprise of the NAFLD data set using the timeline form.
66
all=TRUE)
> # Add in the comorbidities of interest. None of these 4 happen to have
> # duplicates (MI does, for instance).
> # Start by removing the the 13 rows with a "confirmed NAFLD" (actual NAFLD + 1 year)
> # that is after the actual last follow-up date.
> # Treat diabetes before day 0 as diabetes on day 0.
> badrow <- which(nafld3$days > nafld1$futime[match(nafld3$id, nafld1$id)])
> fixnf3 <- nafld3[-badrow,]
> tldata <- merge(tldata, with(subset(fixnf3, event=="diabetes"),
data.frame(id=id, days=pmax(0,days), diabetes=1)),
all=TRUE, by=c("id", "days"))
> tldata <- merge(tldata, with(subset(fixnf3, event=="htn"),
data.frame(id=id, days=pmax(0,days), htn=1)),
all=TRUE, by=c("id", "days"))
> tldata <- merge(tldata, with(subset(fixnf3, event=="dyslipidemia"),
data.frame(id=id, days= pmax(0, days), dyslipid=1)),
all=TRUE, by=c("id", "days"))
> tldata <- merge(tldata, with(subset(fixnf3, event=="nafld"),
data.frame(id=id, days= pmax(0,days), nafld=1)),
by=c("id", "days"), all=TRUE)
> tldata$nafld <- with(tldata, ifelse(is.na(nafld.y), nafld.x, nafld.y))
We want to assume that a subject is non-NAFLD until detection, which means setting nafld
to 0 at time 0; this was done in the rst tldata line above. Ideally, we would have a version
ofmerge that overwrites that value for a subject with NAFLD on day 0, but that is not how
merge works; given any tied days between tldata and xnf3 there will be two variables nafld.x
and nafld.y. The last line above makes one from the two. Initial values for the number of
comorbidities are handled by the cumevent function.
> #
> # For cumulative events within subject we use a helper function
> cumevent <- function(id, time, status, istate) {
# do all the work on ordered data
ord <- order(id, time)
id2 <- id[ord]
time2 <- time[ord]
stat2 <- ifelse(is.na(status[ord]), 0, status[ord])
firstid <- !duplicated(id)
csum <- cumsum(stat2)
indx <- match(id2, id2)
cstat<- csum + stat2[indx] - csum[indx]
cstat[stat2==0] <- 0
67
newdata
}
> temp1 <- rowSums(tldata[,c('diabetes', 'htn', 'dyslipid')], na.rm=TRUE)
> temp2 <- with(tldata, cumevent(id, days, pmax(temp1, 4*death, na.rm=TRUE)))
> state <- factor(pmin(temp2$status, 4), -1:4,
c("censor", paste0(0:3, "mc"), "death"))
> tldata <- merge(tldata, data.frame(id=temp2$id, days=temp2$time, state=state),
all=TRUE)
> tldata$age <- with(tldata, days/365.25 + age[match(id, id)])
> check2 <- survcheck(Surv2(days, state) ~ 1, id=id, tldata)
> check2$transitions
to
from 1mc 2mc 3mc death (censored)
0mc 1829 70 4 263 5705
1mc 0 1843 28 243 4567
2mc 0 0 1048 417 3687
3mc 0 0 0 441 2220
death 0 0 0 0 0
> nfit2 <- coxph(list(Surv2(age, state) ~ nafld + male,
"0mc":state("1mc", "2mc", "3mc") ~ nafld+ male / common,
2:3 + 2:4 ~ nafld + male / common,
0:"death" ~ male / common),
data=tldata, id=id)
> round(coef(nfit2), 3)
nafld_1:2 male_1:2 nafld_2:3 male_2:3 nafld_3:4 male_3:4 nafld_1:5
0.915 0.179 0.521 0.246 0.485 0.149 0.630
male_1:5 nafld_2:5 nafld_3:5 nafld_4:5
0.329 0.534 0.551 0.072
The resulting t it identical to the one that used the counting process data set.
There are advantages and disadvantages to the timeline data as compared to counting process
style.
Counting process style has been available for a long while it was rst incorporated into
the survival package in 1986 and it has been adopted by several other packages. The
format is hence familiar to many users.
Nevertheless, it contains many traps for the unwary. The distinction between outcome and
predictor variables is critical: the former applies at the end of each (time1, time2) interval
and the former at the start of the interval. If one is tting multiple models, one where the
number of comorbid conditions was a predictor and one where it is the outcome, dierent
variables and/or data sets are required. In multi-state data sets separate variables are
needed for the current state and for an event, and they behave dierently.
The tmerge routine simplies some tasks, but it can be subtle. The author/maintainers of
the routine are often puzzled ourselves. When there are multiple possible endpoints and/or
multiple time scales it can get particularly challenging.
68
Timeline data is simpler. There is no distinction between covariates and events, or between
current and next state. Any necessary temporal orderings are created by the underlying
survival models when processing the formula. This makes it easier to get the data set
correct.
Timeline data sets are created using standard tools. The example above used only tools
in base R (a restriction for vignettes in the list of `recommended' packages), but there is a
wide range of available data manipulation tools. The result need only obey the requirement
of having no duplicate (id, timescale) keys. This is a common constraint in relational
databases.
For the constructed variable approach, assume that the true form of the model for variable x1
is β1 (t)x1 , with the coecient having the simple linear form β1 (t) = a + bt. Then
that is, we can create a special time-dependent covariate z = x1 t , add add it to the data set,
and then use an ordinary coxph t.
Consider the veterans lung cancer data set, which has often been used to illustrate non-
proportional hazards. Adding this special covariate is not quite as simple as writing
69
> dtime <- unique(veteran$time[veteran$status==1]) # unique times
> newdata <- survSplit(Surv(time, status) ~ trt + celltype + karno,
data=veteran, cut=dtime)
> nrow(veteran)
[1] 137
> nrow(newdata)
[1] 5959
> fit0 <- coxph(Surv(time, status) ~ trt + celltype + karno, veteran)
> fit1 <- coxph(Surv(tstart, time, status) ~ trt + celltype + karno,
data=newdata)
> fit2 <- coxph(Surv(tstart, time, status) ~ trt + celltype + karno +
time:karno, newdata)
> fit2
Call:
coxph(formula = Surv(tstart, time, status) ~ trt + celltype +
karno + time:karno, data = newdata)
1. The choice β(t) ≈ a + bt was arbitrary. Perhaps the true form is a + b log(t) (t2b above),
or some other function.
70
2. The intermediate data set can become huge. It will be of order O(nd) where d is the
number of unique event times, and d grows along with n.
3. The coecients for a factor variable such as celltype can be confusing, since the results
depend on how the 0/1 indicators for the variable are chosen.
4. Outliers in time are an issue. The veteran cancer data set, for instance, contains a time of
999 days (a particularly suspicious value in any data set). The Cox model itself depends
only on the rank order of the event times, so such outliers are not an issue for the base
model, but as a covariate these values can have undue inuence. The time-dependent
coeent for Karnofsky has p < .01 in t2b above, which uses rank(time), a change that is
largely due to dampening the leverage of outliers.
The cox.zph function checks proportional hazards for a tted Cox model directly, and tries to
address the four issues discussed above.
It is easy to specify alternate time transforms such as x*log(t). More importantly, the code
produces both a diagnostic plot that suggests the shape of any non-proportionality, along
with a test of the chosen time-transform.
The test statistic is based on a score test, which does not require creating the expanded
data set.
Multi-covariate terms such as a factor or splines are by default treated as a single eect.
Shown below are results for the veterans data using fit0 from above. The score statistic for
the simple term x*time (zp1) closely matches the Wald test for the full time dependent t found
in fit2 above, which is what we would expect; score, Wald and likelihood ratio tests usually
agree quite closely for Cox models.
71
> oldpar <- par(mfrow=c(2,2))
> for (i in 1:3) {plot(zp1[i]); abline(0,0, lty=3)}
> plot(zp0[3])
> par(oldpar)
3
6
Beta(t) for celltype
2
4
Beta(t) for trt
2
−1 0
0
−4
−3
1 5 10 50 500 1 5 10 50 500
Time Time
0.05
0.05
Beta(t) for karno
−0.05
−0.15
−0.15
Time Time
A test for zero slope, from a least squares regression using data in the matching plot approx-
imates the score test. (In versions of the package prior to survival3.0, the approximate test was
used for the formal test and printout as well.) If proporitional hazard holds we would expect
the tted line to be horizontal, i.e., β(t) is constant. Rather than show a tted line the plot
adds a general smooth curve, which can help reveal the form of non-proportional hazards, if
it exists. The rst three panels of the plot show curves for the three covariates on a log(time)
scale. Since celltype is a factor, the plot shows the time dependent eect of the portion of the
linear predictor associated with cell type; if proportional hazards is true wrt that term a tted
line should be horizontal with a coecient of 1. The eect of Karnofsky score appears to be-
come essentially 0 after approximately 6 months; for this cohort of subjects with advanced lung
cancer, a 6 month old assessment of Karnofsky is no longer relevant. The corresponding plot in
the lower right panel, however, shows that the outlier time of 999 days has an undue inuence
on any such regression. A test of proportional hazards on that scale must also be treated with
caution. The plot using log scale lacks these outliers and is more interpretable.
The default time transform is based on a Kaplan-Meier transform, i.e., that monotone trans-
form of the time axis that will cause the KM plot to be a straight line. This is a good default for
the score tests, since it essentially guarrantees that there wil be no outliers in the constructed
xg(time) variable, while dealing with censoring in a defensible way. That is, the code has opted
72
for a safe default. It is not as easily interpreted as other scales for the plots, however.
The cox.zph function does not attempt a score test for random eects (frailty) terms, in
fact is not clear what the computation for such a test should be. The function will check other
covariates in a model that contains a random eect, however; in that test the estimated random
eect per subject is essentially treated as a xed oset.
The score test is simple in theory, but the devil is in the details as they say. Consider adding the
constructed variables for celltype to the t. That is g(t)*x2, g(t)*x3, g(t)*x4, where x2-x4 are
the three dummy variables that represent celltype. The new model has 5 + 3 covariates, and is
evaluated at (β̂, 0, 0, 0). The score statistic at this coecient value will be (0, 0, 0, 0, 0, u6 , u7 , u8 ),
the rst 5 elements are zero since that is the denition of model convergence for β̂ .
The information or Hessian matrix for a Cox model is
X X
V (tj ) = Vj
j∈deaths j
where Vj is the variance matrix of the weighted covariate values, over all subjects at risk at time
tj . Then the expanded information matrix for the score test is
H1 H2
H =
H2′ H3
X
H1 = V (tj )
X
H2 = V (tj )g(tj )
X
H3 = V (tj )g 2 (tj )
The inverse of the matrix will be more numerically stable if g(t) is centered at zero, and this does
not change the test statistic. In the usual case V (t) is close to constant in time the variance
of X does not change rapidly and then H2 is approximately zero. The original cox.zph used
an approximation, which is to assume that V (t) is exactly constant. In that case H2 = 0 and
g 2 (tj ) and the test is particularly easy to compute.
P P
H3 = V (tj ) This assumption of identical
components can fail badly for models with a covariate by strata interaction, and for some models
with covariate dependent censoring.
If there are p covariates, the new score vector will be of length 2p and the information matrix
will be 2p by 2p. These can be computed using a simple variant of the C code for coxph;
no iteration is done. In fact, the use of time-weighted risk sets has been proposed by several
authors, for multiple rationales. This has not been implemented in the coxph routine (but we
have thought about it).
The score tests are done for single covariates or terms. Using the veteran example, a test
for celltype as a term would rst select rows 1-5 and 7-9 of the score vector U and information
matrix H; j <- c(1:5, 7:9) the test is U[j] %*% inverse(H[j,j]) %*% U[j]. (This
i.e., if
is done using the the solve function of course, rather than taking an explicit inverse). The result
is a 3 degree of freedom chisquare statistic. For a single variable test, the fact that only a single
element of U[j] is non-zero allows for a faster shortcut calculation.
A few further things need to be considered.
73
1. There may be NA coecients in the t, e.g., for a model that has redundant variables in
its X matrix. It is fairly simple to keep track of these, and remove any such from our set
of variables j.
2. There is not a good dention of how to test PH for a random eects term, e.g., from a
coxme model or a copxh t with a frailty term. For these, we treat the resultant random
coecients as though they were xed, and test the other variable under this constraint.
3. For a penalized model, the penalty is assumed to apply to both the original and to then
extended coecients. However,
Penalties depend only the coecient hatβ , not on the data or the time weights.
All the penalties that we support are 0 at β = 0, and have a rst derivative of 0 there,
so there is no impact on the score vector U . U is 0 for the current covariates, by
denition, and the new ones are being evaluated at 0.
There will be an impact on the second derivative, however. But this will by denition
be idential to the penalty for the original variables.
4. The most dicult issue is use of a robust variance in the original model. This requires
not just the score vector U, but the nbyp matrix of of dfbeta residuals D. This requires a
special version of the relevant C routine; there are no simple computaional shortcuts.
74
Chapter 4
4.1 Usage
The survreg function implements the class of parametric accelerated failure time models. As-
sume that the survival time y satises log(y) = X ′ β + σW , for W from some given distribution.
Then if Λw (t) is the cumulative hazard function for W , the cumulative hazard function for sub-
ject i is Λw [exp(−ηi /σ)t], that is, the time scale for the subject is accelerated by a constant
factor. A good description of the models is found in chapter 3 of Kalbeisch and Prentice [4].
The following ts a Weibull model to the lung cancer data set included in the package.
> fit <- survreg(Surv(time, status) {\twiddle} age + sex + ph.karno, data=lung,
dist='weibull')
> fit
Call:
survreg(formula = Surv(time, status) {\twiddle} age + sex + ph.karno, data = lung, dist
= "weibull")
Coefficients:
(Intercept) age sex ph.karno
5.326344 -0.008910282 0.3701786 0.009263843
Scale= 0.7551354
75
4.2 Strata
In a Cox model the strata statement is used to allow separate baseline hazards for subgroups
of the data, while retaining common coecients for the other covariates across groups. For
parametric models, the statement allows for a separate scale parameter for each subgroup, but
again keeping the other coecients common across groups. For instance, assume that separate
baseline hazards were desired for males and females in the lung cancer data set. If we think of
the intercept and scale as the baseline shape, then an appropriate model is
Scale:
sex=1 sex=2
0.8165161 0.6222807
76
4.4 Specifying a distribution
The tting routine is quite general, and can accept any distribution that spans the real line
for W, and any monotone transformation of y. The standard set of distributions is contained
in a list survreg.distributions. Elements of the list are of two types. Basic elements are a
description of a distribution. Here is the entry for the logistic family:
logistic = list(
name = "Logistic",
variance = function(parm) pi^2/3,
init = function(x, weights, ...) \{
mean <- sum(x*weights)/ sum(weights)
var <- sum(weights*(x-mean)^2)/ sum(weights)
c(mean, var/3.2)
\},
deviance= function(y, scale, parms) \{
status <- y[,ncol(y)]
width <- ifelse(status==3,(y[,2] - y[,1])/scale, 0)
center <- y[,1] - width/2
temp2 <- ifelse(status==3, exp(width/2), 2) #avoid a log(0) message
temp3 <- log((temp2-1)/(temp2+1))
best <- ifelse(status==1, -log(4*scale),
ifelse(status==3, temp3, 0))
list(center=center, loglik=best)
\},
density = function(x, ...) \{
w <- exp(x)
cbind(w/(1+w), 1/(1+w), w/(1+w)^2, (1-w)/(1+w), (w*(w-4) +1)/(1+w)^2)
\},
quantile = function(p, ...) log(p/(1-p))
)
Variance contains the variance of the distribution. For distributions with an optional
parameter such as the t-distribution, the parm argument will contain those parameters.
Deviance gives a function to compute the deviance residuals. More on this is explained
below in the mathematical details.
The density function gives the necessary quantities to t the distribution. It should return
a matrix with columns F (x), 1 − F (x), f (x), f ′ (x)/f (x) and f ′′ (x)/f (x), where f′ and f ′′
are the rst and second derivatives of the density function, respectively.
The reason for returning both F and 1−F in the density function is to avoid round o error
when F (x) is very close to 1. This is quite simple for symmetric distributions, in the Gaussian
77
case for instance we use qnorm(x) and qnorm(-x) respectively. (In the intermediate steps of
iteration very large deviates may be generated, and a probabilty value of zero will cause further
problems.)
Here is an example of the second type of entry:
exponential = list(
name = "Exponential",
dist = "extreme",
scale =1 ,
trans = function(y) log(y),
dtrans= function(y) 1/y ,
itrans= function(x) exp(x)
)
This states that an exponential t is computed by tting an extreme value distribution to the log
transformation of y. (The distribution pointed to must not itself be a pointer to another). The
extreme value distribution is restricted to have a scale of 1. The rst derivative of the transfor-
mation, dtrans, is used to adjust the nal log-likelihood of the model back to the exponential's
scale. The inverse transformation itrans is used to create predicted values on the original scale.
The formal rules for an entry are that it must include a name, either the dist" component
or the set variance",init", deviance", density" and quantile", an optional scale, and either
all or none of trans", dtrans" and itrans".
The dist="weibull" argument to the survreg function chooses the appropriate list from
the survreg.distributions object. User dened distributions of either type can be specied by
supplying the appropriate list object rather than a character string. Distributions should, in
general, be dened on the entire real line. If not the minimizer used is likely to fail, since it has
no provision for range restrictions.
Currently supported distributions are
basic
Exponential
Weibull
Log-logistic ('loglogistic')
78
4.5 Residuals
4.5.1 Response
The target return value is y − ŷ , but what should we use for y when the observation is not exact?
We will let ŷ0 be the MLE for the location parameter µ over a data set with only the observation
of interest, withσ xed at the solution to the problem as a whole, subject to the constraint that
µ be consistent with the data. That is, for an observation right censored at t = 20, we constain
µ ≥ 20, similarly for left censoring, and constrain µ to lie within the two endpoints of an interval
censored observation. To be consistent as the width of an interval censored observation goes to
zero, this denition does require that the mode of the density lies at zero.
For exact, left, and right censored observations ŷ0 = y , so that this appears to be an ordinary
response residual. For interval censored observations from a symmetric distribution, ŷ0 = the
center of the censoring interval. The only unusual case, then, is for a non-symmetric distribution
such as the extreme value. As shown later in the detailed information on distributions, for the
extreme value distribution this occurs for ŷ0 = y l − log(b/[exp(b) − 1]), where b = yu − yl is the
length of the interval.
4.5.2 Deviance
Deviance residuals are response residuals, but transformed to the log-likelihood scale.
p
di = sign(ri ) LL(yi , ŷ0 ; σ) − LL(yi , ηi ; σ)
The denition for ŷ0 used for response residuals, however, could lead to the square root of a
negative number for left or right censored observations, e.g., if the predicted value for a right
censored observation is less than the censoring time for that observation. For these observations
we let ŷ0 be the unconstrained maximum, which leads to yhat0 = −∞ and +∞ for right and
left censored observations, respectively, and a log-likelihood term of 0.
The advantages of these residuals for plotting and outlier detection are nicely detailed in
McCullagh and Nelder [7]. However, unlike GLM models, deviance residuals for interval censored
data are not free of the scale parameter. This means that if there are interval censored data
values and one ts two models A and B, say, that the sum of the squared deviance residuals for
model A minus the sum for model B is not equal to the dierence in log-likelihoods. This is one
reason that the current survreg function does not inherit from class glm: glm models use the
deviance as the main summary statistic in the printout.
4.5.3 Dfbeta
The dfbeta residuals are a matrix with one row per subject and one column per parameter.
The ith row gives the approximate change in the parameter vector due to observation i, i.e.,
the change in β̂ when observation i is added to a t based on all observations but the ith.
The dfbetas residuals scale each column of this matrix by the standard error of the respective
parameter.
79
4.5.4 Working
As shown in section 4.7 below, the Newton-Raphson iteration used to solve the model can be
viewed as an iteratively reweighted least squares problem with a dependent variable of current
prediction - correction. The working residual is the correction term.
Escobar and Meeker [1] dene a matrix of likelihood displacement residuals for the accelerated
failure time model. The full residual information is a square matrix Ä, with dimension the
number of pertubations considered. Three examples are developed in detail, all with dimension
n, the number of observations.
Case weight pertubations measure the overall eect on the parameter vector of dropping a
case. Let V L the n by p matrix with elements ∂Li /∂βj ,
be the variance matrix of the model, and
′
where Li is the likelihood contribution of the ith observation. Then Ä = LV L . The residuals
function returns the diagonal values of the matrix. Note that LV equals the dfbeta residuals.
Response pertubations correspond to a change of 1 σ unit in one of the response values. For
a Gaussian linear model, the equivalent computation yields the diagonal elements of the hat
matrix.
Shape pertubations measure the eect of a change in the log of the scale parameter by 1 unit.
The matrix residual type returns the raw values that can be used to compute these and other
LD inuence measures. The result is an n by 6 matrix, containing columns for
The linear predictor is ηi = x′i β̂ , where xi is the covariate vecor for subject i and β̂ is the nal
parameter estimate. The standard error of the linear predictor is x′i V xi , where V is the variance
matrix for β̂ .
The predicted response is identical to the linear predictor for ts to the untransformed dis-
tributions, i.e., the extreme-value, logistic and Gaussian. For transformed distributions such as
the Weibull, for which log(y) is from an extreme value distribution, the linear predictor is on the
transformed scale and the response is the inverse transform, e.g. exp(ηi ) for the Weibull. The
standard error of the transformed response is the standard error of ηi , times the rst derivative
of the inverse transformation.
4.6.2 Terms
Predictions of type terms are useful for examination of terms in the model that expand into
multiple dummy variables, such as factors and p-splines. The result is a matrix with one column
for each of the terms in the model, along with an optional matrix of standard errors. Here is an
example using psplines on the 1980 Stanford data
80
> fit <- survreg(Surv(time, status) ~ pspline(age, df=3) + t5, stanford2,
dist='lognormal')
> tt <- predict(fit, type='terms', se.fit=T)
> yy <- cbind(tt$fit[,1], tt$fit[,1] -1.96*tt$se.fit[,1],
tt$fit[,1] +1.96*tt$se.fit[,1])
> matplot(stanford2$age, yy, type='l', lty=c(1,2,2))
4.6.3 Quantiles
If predicted quantiles are desired, then the set of probability values p must also be given to the
predict function. A matrix of n rows and p columns is returned, whose ij element is the pj th
quantile of the predicted survival distribution, based on the covariates of subject i. This can be
written as Xβ + zq σ wherezq is the q th quantile of the parent distribution. The variance of the
quantile estimate is then cV c′ where V is the variance matrix of (β, σ) and c = (X, zq ).
In computing condence bands for the quantiles, it may be preferable to add standard errors
on the untransformed scale. For instance, consider the motor reliability data of Kalbeisch and
Prentice [5].
81
Using the (default) Weibull model, the data is t on the log(y) scale. The condence bands
obtained by the second method are asymmetric and may be more reasonable. They are also
guarranteed to be > 0.
This example reproduces gure 1 of Escobar and Meeker [1].
where exact, right, left, and interval refer to uncensored, right censored, left censored,
and interval censored observations, respectively, and zil , ziu are the lower and upper endpoints,
respectively, for an interval censored observation. Then the log likelihood is dened as
X X X X
LL = g1 (zi ) − log(σ) + g2 (zi ) + g3 (zi ) + g4 (zi , zi∗ ) , (4.1)
exact right lef t interval
82
Derivatives of the LL with respect to the regression parameters are:
n
∂LL X ∂g ∂ηi
=
∂βj i=1
∂ηi ∂βj
n
X ∂g
= xij (4.2)
i=1
∂ηi
∂ 2 LL X ∂2g
= xij xik , (4.3)
∂βj βk ∂ηi2
(X T DX)δ = X T U,
where D is the diagonal matrix formed from −g ′′ , and U is the vector g′ . The current estimate
β satises Xβ = η , so that the new estimate β + δ will have
(X T DX)(β + δ) = X T Dη + X T U
= (X T D)(η + D−1 U )
Thus if we treat σ as xed, iteration is equivalent to IRLS with weights of −g ′′ and adjusted
′ ′′
dependent variable of η − g /g . At the solution to the iteration we might expect that η̂ ≈ y ;
and a weighted regression with y replacing η gives, in general, good starting estimates for the
iteration. (For an interval censored observation we use the center of the interval as `y'). Note
that if all of the observations are uncensored, then this reduces to using the linear regression
of y on X as a starting estimate: y=η so z = 0, thus g′ = 0 and g ′′ = a constant (all of the
supported densities have a mode at zero).
This clever starting estimate is introduced in Generalized Linear Models (McCullagh and
Nelder [7]), and works extremely well in that context: convergence often occurs in 3-4 iterations.
It does not work quite so well here, since a good" t to a right censored observation might have
η >> y . Secondly, the other coecients are not independent of σ, and σ often appears to be the
most touchy variable in the iteration.
Most often, the routines will be used with log(y), which corresponds to the set of accelerated
failure time models. The transform can be applied implicitly or explicitly; the following two ts
give identical coecients:
83
4.8 Derivatives
This section is very similar to the appendix of Escobar and Meeker [1], diering only in our use of
log(σ) rather than σ as the natural parameter. Let f and F denote the density and distribution
functions, respectively, of the distributions. Using (4.1) as the denition of g1, . . . , g4 we have
1 f ′ (z)
∂g1
= −
∂η σ f (z)
1 f (z u ) − f (z l )
∂g4
= −
∂η σ F (z u ) − F (z l )
2
1 f ′′ (z)
∂ g1
= − (∂g1 /∂η)2
∂η 2 σ 2 f (z)
∂ 2 g4 1 f ′ (z u ) − f ′ (z l )
= − (∂g4 /∂η)2
∂η 2 σ 2 F (z u ) − F (z l )
′
∂g1 zf (z)
= −
∂ log σ f (z)
u
z f (z u ) − z l f (z l )
∂g4
= −
∂ log σ F (z u ) − F (z l )
2 ′′
∂ 2 g1 z f (z) + zf ′ (z)
= − (∂g1 /∂ log σ)2
∂(log σ)2 f (z)
u 2 ′ u
∂ 2 g4 (z ) f (z ) − (z l )2 f ′ (zl )
= − ∂g1 /∂ log σ(1 + ∂g1 /∂ log σ)
∂(log σ)2 F (z u ) − F (z l )
∂ 2 g1 zf ′′ (z)
= − ∂g1 /∂η(1 + ∂g1 /∂ log σ)
∂η∂ log σ σf (z)
∂ 2 g4 z u f ′ (z u ) − z l f ′ (z l )
= − ∂g4 /∂η(1 + ∂g4 /∂ log σ)
∂η∂ log σ σ[F (z u ) − F (z l )]
To obtain the derivatives for g2 , set the upper endpoint zu to ∞ in the equations for g4 . To
obtain the equations for g3 , left censored data, set the lower endpoint to −∞.
After much experimentation, a further decision was made to do the internal iteration in
terms of log(σ). This avoids the boundary condition at zero, and also helped the iteration speed
considerably for some test cases. The changes to the code were not too great. By the chain rule
∂LL ∂LL
= σ
∂ log σ ∂σ
∂ 2 LL ∂ 2 LL ∂LL
= σ2 +σ
∂(log σ)2 ∂σ 2 ∂σ
∂ 2 LL ∂ 2
= σ
∂η∂ log σ ∂η∂σ
At the solution ∂LL/∂σ = 0, so the variance matrix for σ is a simple scale change of the returned
matrix for log(σ).
84
4.9 Distributions
4.9.1 Gaussian
Everyone's favorite distribution. The continual calls to Φ may make it slow on censored data,
however. Because there is no closed form for Φ, only the equations for g1 simplify from the
general form given in section 2 above.
µ=0 , σ2 = 1
F (z) = Φ(z)
√
f (z) = exp(−z 2 /2)/ 2π
f ′ (z) = −zf (z)
f ′′ (z) = (z 2 − 1)f (z)
For uncensored data, the standard glm results are clear by substituting g1 = −z/σ into equations
1-5. The rst derivative vector is equal to X ′ r where r = −z/σ is a scaled residual, the update
step I −1 U is independent of the estimate
2
of σ , and the maximum likelihood estimate of nσ is
the sum of squared residuals. None of these hold so neatly for right censored data.
If y is Weibull then log(y) is distributed according to the (least) extreme value distribution.
As stated above, ts on the latter scale are numerically preferable because it removes the range
restriction on y. A Weibull distribution with the scale restricted to 1 gives an exponential model.
µ = −γ = .5722 . . . , σ 2 = π 2 /6
F (z) = 1 − exp(−w)
f (z) = we−w
′
f (z) = (1 − w)f (z)
′′
f (z) = (w2 − 3w + 1)f (z)
where w ≡ exp(z).
The mode of the distribution is at f (0) = 1/e, so for an exact observation the deviance term
has ŷ = y . For interval censored data where the interval is of length b = z u − z l , it turns out
that we cover the most mass if the interval has a lower endpoint of a = log(b/(exp(b) − 1))), and
the resulting log-likelihood is
a a+b
log(e−e − e−e ).
Proving this is left as an exercise for the reader.
The cumulative hazard for the Weibull is usually written as Λ(t) = (at)p . Comparing this
to the extreme value we see that p = 1/σ and a = exp(−η). (On the hazard scale the change
of variable from t to log(t) adds another term). The Weibull can be thought of as both an
accelerated failure time model, with acceleration factor a or as a proportional hazards model
with constant of proportionality ap . If a Weibull model holds, the coecients of a Cox model
85
will be approximately equal to −β/σ , the latter coming from a survreg t. The change in
sign reects a change in perspective: in a proportional hazards model a positive coecient
corresponds to an increase in the death rate (bad), whereas in an accelerated failure time model
a positive coecient corresponds to an increase in lifetime (good).
4.9.3 Logistic
This distribution is very close to the Gaussian except in the extreme tails, but it is easier to
compute. However, some data sets may contain survival times close to zero, leading to dierences
in t between the lognormal and log-logistic choices. (In such cases the rationality of a Gaussian
t may also be in question). Again let w = exp(z).
µ = 0, σ 2 = π 2 /3
F (z) = w/(1 + w)
f (z) = w/(1 + w)2
f ′ (z) = f (z) (1 − w)/(1 + w)
′′
f (z) = f (z) (w2 − 4w + 1)/(1 + w)2
The distribution is symmetric about 0, so for an exact observation the contribution to the
deviance term is − log(4). For an interval censored observation with span 2b the contribution is
eb − 1
log (F (b) − F (−b)) = log .
eb + 1
Some other population hazards can be t into this location-scale framework, some can not.
Distribution Hazard
Weibull pλ(λt)p−1
Extreme value (1/σ)e(t−η)/σ
Rayleigh a + bt
Gompertz bct
Makeham a + bct
The Makeham hazard seems to t human mortality experience beyond infancy quite well,
where a is a constant mortality which is independent of the health of the subject (accidents,
homicide, etc) and the second term models the Gompertz assumption that the average exhaus-
tion of a man's power to avoid death is such that at the end of equal innitely small itervals of
time he has lost equal portions of his remaining power to oppose destruction which he had at
the commencement of these intervals". For older ages a is a neglible portion of the death rate
and the Gompertz model holds.
Clearly
The Wiebull distribution with p = 2 (σ = .5) is the same as a Rayleigh distribution with
a = 0. It is not, however, the most general form of a Rayleigh.
86
The extreme value and Gompertz distributions have the same hazard function, with σ=
1/ log(c), and exp(−η/σ) = b.
It would appear that the Gompertz can be t with an identity link function combined with the
extreme value distribution. However, this ignores a boundary restriction. If f (x; η, σ) is the
extreme value distribution with paramters η and σ, then the denition of the Gompertz densitiy
is
g(x; η, σ) = 0 x<0
g(x; η, σ) = cf (x; η, σ) x >= 0
where c = exp(exp(−η/σ)) is the necessary constant so that g integrates to 1. If η/σ is far from
1, then the correction term will be minimal and the above t will be a good approximation to
the Gompertz.
The Makeham distribution falls into the gamma family (equation 2.3 of Kalbeisch and
Prentice, Survival Analysis), but with the same range restriction problem.
87
Chapter 5
88
Let the risk scores exp(Xβ) for the 12 subjects be r1 r12 , and assume that the two failures
actually at month 5 are not tied on a ner time scale. For the rst event, whichever it is, the risk
P
set with be all subjects 112 and the denominator of the partial likelihood term is ri . For the
second event, the denominator is either r1 +r3 +. . . r12 or r2 +r3 +. . . r12 ; the Efron approximation
is to use the average of the two as the denominator term. In the software this is easily done
by using temporary case weights: if there were k tied events then one of the denomiators gives
each of those k subjects a weight of 1, then next gives each a weight of (k − 1)/k , then next a
weight of (k − 2)/k , etc. The Efron approximation imposes a tiny bit more bookkeeping, but the
the computational burden is no dierent that for case weights; i.e., it eectively takes no more
computational time than the Breslow approximation.
The third possiblility is the exact partial likelihood due to Cox, which treats the underlying
time scale as discrete rather than continuous. When taking this view the denominator of the
partial likelihood term is again an average, but over a much larger subset. If there are k events
and n subjects at risk, the EPL sum is over all k choose n possible choices. In the AML example
above, the event at time 5 will be a sum over 12(11)/2= 33 terms. If the number of ties is large
this quickly grows unreasonable: for 20 ties out of 1000 the sum has over 39 billion terms. A
clever algorithm by Gail makes this sum barely possible, but it does not extend to the case of
(tstart, tstop) style data.
An important aside is that the log-likelihood for matched logistic regression is identical to
the Cox partial likelihood for a particular data set, when the EPL is used. Namely, set time=1
(or any other constant), status = 0 for controls and 1 for cases, and t a coxph model with each
matched set as a separate stratum. In most instances a matched set will consist of a single case
along with one or more controls, however, which is the case where the Breslow, Efron, and EPL
are identical. (The EPL will still take slightly longer to run due to setting up the necessary
structure for all those sums.)
How important are the ties, actually? Below we show a small computation in which a larger
data set is successively coarsened and compare the results. The colon cancer data set has 929
subjects with stage B/C colon cancer who were randomized to three treatment arms and then
followed for 5 years; the time to death or progression is in days. In the example below we
successively coarsen the time scale to be monthly, bimonthly, . . . , bi-annual; the last of which
generates an very large number of ties. What we see is that
The Efron approximation is quite good at dealing with the coarsened data, producing
nearly the same coecient as the original data even when the coarsening is extreme.
The Breslow approximation is biased somewhat towards 0, the exact paritial likelihood
somewhat away from 0.
The dierences are very small. With monthly coarsening, which is itself fairly large, the 3
estimates dier by about .01 while the standard error of the original coecient is 0.96; i.e.
a shift that is statistically immaterial.
89
temp <- floor(tdata$time/scale)
tfit <- coxph(Surv(temp, status) ~ node4 + extent, tdata)
tfit2 <- coxph(Surv(temp, status) ~ node4 + extent, tdata,
ties='breslow')
tfit3 <- coxph(Surv(temp, status) ~ node4 + extent, tdata,
ties='exact')
cmat[i,] <- c(coef(tfit2), coef(tfit), coef(tfit3))
}
> matplot(1:7, cmat[,c(1,3,5)], xaxt='n', pch='bec',
xlab="Time divisor", ylab="Coefficient for node4")
> axis(1, 1:7, c(1, floor(1:6 *365/12)))
c
0.88
c
c
0.86
Coefficient for node4
c
c e
0.84
c
e
b e e
e e
b e
0.82
b
b
0.80
b b
0.78
Time divisor
Early on in the package the decision was made to make the Efron approximation the default.
The reasoning was simply that is is more accurate, even if only a little, and the author's early
background in numerical analysis argued strongly to always use the best approximation available.
The second reason is that the computational cost is low. Most of us would pick up a 1 Euro
coin on the sidewalk, even though it will not make any real change in our income. One downside
is that no other package did this, leading to a very common complaint/question that R gives
dierent results. A second is that it leads to further downstream programming as discussed in
following sections.
90
5.2 Cumulative hazard and survival
The coarsening argument can also be applied to the cumulative hazard Λ(t). Say that there
were 3 deaths with 10 subjects at risk. The increment to the Nelson-Aalen cumulative hazard
estimate would then be 3/10. If the data had been observed in continuous time, however, there
would have been 3 increments of 1/10 + 1/9 + 1/8. This estimate was explored by Fleming and
Harrington [2]. In the survfit function the ctype option selects for 1=Nelson-Aalen and 2=
Fleming-Harrington.
The Kaplan-Meier estimate is not subject to the coarsening phenominon. In our example, the
observed data will lead to a multipilicative increment of 7/10 and the continuous data to one of
(9/10)(8/9)(7/8), which are the same. An alternate estimate of the survival is S(t) = exp(−Λ(t)).
Basing this on the FH estimate of hazard will more closely track the KM when there are tied event
times. The direct (KM) vs. exponential estimates of survival are obtained with the ctype=1
and ctype=2 arguments; however, the exponential estimate is quite uncommon outside of the
Cox model.
Z t P
dNi (t)
Λ̂(t) = Pi (5.1)
0 i Yi (t)ri
Equation (5.1) is known as the Breslow estimate; if β̂ = 0 then ri = 1 and it becomes equal to
the Nelson-Aalen estimator.
If the Efron estimate is used for ties, then the software uses an Efron estimate of the cumula-
tive hazard; which reduces to the Fleming-Harrington if β̂ = 0. Using the hazard estimate that
matches the parial likelihood estimate causes an important property of the vector of martingale
residuals m to hold, namely that mX is equal to the rst derivative of the partial likelihood.
residuals hold for both
The Cox model is a case where the default estimate of survival is based on the exponent of
the cumulative hazard, rather than a 'direct' one such as the Kaplan-Meier. There are three
reasons for this.
P P P
1. The most obvious 'direct' estimate is to use ( dNi (t) − Yi (t)ri )/( Yi (t)ri ) as a mul-
tiplicative update at each event time t. This expression in not guarranteed to be between
0 and 1, however, particular for new subjects who are near or past the boundaries of the
original data set. This leads to using some sort of ad hoc correction to avoid failure.
91
2. The direct estimate of Kalbeisch and Prentice avoids this, but it does not extend to
delayed entry, multi-state models or other extensions of the basic model.
92
Chapter 6
Multi-state models
Multi-state hazards models have a very interesting (and useful) property, which is that hazards
can be estimated singly (without reference to any other transition) but probability-in-state esti-
mators must be computed globally. Thus, one can estimate non-parametric cumulative hazard
estimates (Nelson-Aalen), the hazard ratios for any given transtion (Cox model) or the predicted
cumulative hazard function based on a per transition Cox model without incurring any issues
with respect to competing risks. (If there is informative censoring the overall and individual es-
timates still agree, but they will both be wrong. An example of informative censoring would be
subjects who are removed from the data because of an impending event, e.g., censoring subjects
who enter hospice care would underestimate death rates.)
Now say that we had a simple competing risks problem, 10 subjects are alive and in the
initial state on day 100, at which time two of them transition to two dierent endpoints. A
coarsening argument would say that on the underlying continuous time scale these two subjects
would not be tied, and then would use 9.5 as the denominator for each of the two cumulative
hazard increments. Such an estimate would however then be at variance with the two indiviually
computed hazards: global coarsening removes the separability. The survival package takes a
moderated view and will apply the coarsening argument separately to each hazard, i.e., it chose
to retain the separation policy.
93
Appendix A
1. If there are tied event times, to estimate the hazard using a straightforward increment
of (number of events)/(number at risk), or make a correction for the ties. The simpler
method is known variously as the Nelson, Aalen, Breslow, and Tsiatis estimate, along with
hyphenated forms combining 2 or 3 of these labels. One of the simpler corrections for ties is
known as the Fleming-Harrington approximation when used with raw data, and the Efron
when used in a Cox model.
2. The survival curve S(t) can be estimated directly or as the exponential of the cumulative
hazard estimate. The rst of these is known as the Kaplan-Meier, cumulative incidence
(CI), Aalen-Johansen, and Kalbeisch-Prentice estimate, depending on context, the second
as a Fleming-Harrington, Breslow, or Efron estimate, again depending on context.
With respect to the two above, subtypes of the survfit routine have had either a type or
method argument over the years which tried to capture both of these at the same time, and
consequently have had a bewildering number of options, for example eming-harrington in
survfit.formula stood for the simple cumulative hazard estimate plus the exponential survival
estimate, fh2 specied the tie-corrected cumulative hazard plus exponential survival, while
survfit.coxph used breslow and efron for the same two combinations. The updated routines
now have separate stype and ctype arguments. For the rst, 1= direct and 2=exponent of the
cumulative hazard and for the second, 1=simple and 2= corrected for ties.
The Cox model is a special case in two ways: 1. the the way in which ties are treated in
the likelihood should match the way they are treated in creating the hazard and 2. the direct
estimate of survival can be very dicult to compute. The survival package's default is to use the
94
ctype option which matches the ties option of the coxph call along with an exponential estimate
of survival. This ctype choice preserves some useful properties of the martingale residuals.
A second issue is multiple observations per subject, and how those impact the computations.
This leads to 3 common arguments:
id: an identier in each row of the data, which allows the routines to identify multiple rows
for a subject
cluster: identify correlated rows, which should be combined when creating the robust
variance
These arguments have been inconsistent in the past, partly because of the sequential ap-
pearance of multiple use cases. The package started with only the simplest data form: one
observation per subject, one endpoint. To this has been added:
Case (a) arises as a way to code time-dependent covariates, and in this case an id statement
is not needed, and in fact you will get the same estimates and standard errors with or without
it. (There will be a change in the counts of subjects who leave or enter an interval, since an
observation pair (0, 10), (10, 20) for the same subject will not count as an exit (censor) at 10
along with an entry at 10.) If (b) is true then the robust variance is called for and one will
want to have either a cluster argument or the robust=TRUE argument. In the coxph routine,
a cluster(group) term in the model statement can be used instead of the cluster argument,
but this is no longer the preferred form. When (b) and (c) are true then the id statement is
required in order to obtain a correct estimate of the result. This is also the case for (c) alone
when subjects do not all start in the same state. For competing risks data multiple endpoints,
everyone starts in the same state, only one transition per subject the id statement is not
necessary nor (I think) is a robust variance.
When there is an id statement but no cluster or robust directive, then the programs will
use (b) as a litmus test to decide between model based or robust variance, if possible. (There
are edge cases where only one of the two variance estimates has been implemented, however). If
there is a cluster argument then robust=TRUE is assumed. If only a robust=TRUE argument is
given then the code treats each line of data as independent.
A.2 Survt
There has been a serious eort to harmonize the various survt methods. Not all paths had the
same options or produced the same outputs.
95
If stype=1 then the survival curve S(t) is produced directly, if stype=2 it is created
as the exp(-H) where H is the cumulative hazard.
If ctype=1 the Nelson-Aalen formula is used, and for ctype=2 there is a correction
for ties.
The usual curve for a Cox model using the Efron approximate is (2,2), for instance,
while the ordinary non-parametric KM is (1, 1).
The routines now produce both the estimated survival and the estimated cumulative haz-
ard, along with their errors
Some code paths produce std(S) and some std(log(S)), the object now contains a log.se
ag telling which. (Before, downstream routines just had to know).
using a single subscript on a survt object now behaves like the use of a single subscript
on an array or matrix, in that the result has only one dimension.
A utility function survfit0 is used by the print and plot methods to add a starting time 0
value, normally x=0, y=1, to the survival curve(s). It also aligns all the matrices so that they
correspond to the time vector, inserts the correct standard errors, etc. This may be useful to
other programs.
A.3 Coxph
The multi-state objects include astates vector, which is a simple list of the state names. The
cmap component is an integer matrix with one row for each term in the model and one column for
each transition. Each element indexes a position in the coecient vector and variance matrix.
Column labels are of the form 1:2, which denotes a transition from state[1] to state[2].
If a particular term in the data, age say, was not part of the model for a particular
transition then a 0 will appear in that position of cmap.
If two transitions share a common coecient, both those element of cmap will point to the
same location.
Following the coecient information will be a row labeled (Baseline), which contains
integers identing which transitions do or do not share their baseline hazard.
Following this are rows for each strata term (if any) in the model, each a 0/1 vector which
marks transitions to which this strata applies.
96
Bibliography
[1] L.A. Escobar and Jr. Meeker W.Q. Assessing inuence in regression analysis with censored
data. Biometrics, 48:50728, 1992.
[2] T. R. Fleming and D. P. Harrington. Nonparametric estimation of the survival distribution
in censored data. Comm. Stat. Theory Methods, 13:24692486, 1984.
[3] P.J. Green. Iteratively reweighted least squares for maximum likelihood estimation, and some
robust and resistant alternatives (with discussion). J. Royal Stat. Soc. B, 46:149192, 1984.
[4] J. D. Kalbeisch and R. L. Prentice. The Statistical Analysis of Failure Time Data. Wiley,
New York, 1980.
[5] J. D. Kalbeisch and R. L. Prentice. The Statistical Analysis of Failure Time Data, second
edition. Wiley, 2002.
97