Skip to main content
v2026.11,986 entries · CC-BY 4.0

Time-Varying Covariate: Definition, Long-Format Data and a Cox Example

A time-varying covariate changes during follow-up. Learn the long data format, the Cox formula and a worked example with R and Python code.

Written and maintained by CASRAI Editorial Board

Published

On this page

A time-varying covariate is a predictor whose value changes for the same person during follow-up, such as treatment status, smoking status or a repeated lab measurement. In survival analysis it is handled by splitting each person’s follow-up into intervals, one row per stretch with a constant covariate value, and fitting a Cox model that lets the covariate take its current value at each event time (Zhang et al., 2018).

What is a time-varying covariate?

Zhang and colleagues describe time-varying covariates as occurring “when a given covariate changes over time during the follow-up period” and note that the data must be organised in a counting-process style for the Cox model. A fixed covariate, such as sex recorded at enrolment, has one value per person. A time-varying covariate has a value per person per moment. Using only the value recorded at baseline ignores how the covariate moved afterwards; Zhang et al. use smoking status as the example of a variable that keeps changing during follow-up, so a single baseline value fails to describe the exposure the person actually had.

This page covers the survival-analysis meaning of the term, which is how it is used most often, and the long-format data layout every software package needs. For the model itself, see the guide to the Cox proportional hazards model.

Time-varying covariate vs time-varying coefficient

The two ideas are easy to confuse. A time-varying covariate X(t) changes its value during follow-up while its coefficient stays constant. A time-varying coefficient means the effect of a covariate changes with time, which is the same thing as the proportional hazards assumption failing for that covariate. Zhang et al. state that checking proportional hazards is “the same as identifying time-varying coefficients”, and that a coefficient of the form β·g(t) can be rewritten as a model with the time-varying covariate g(t)·X and a constant coefficient. In practice, that is why the same long-format machinery is used for both problems.

Internal and external time-varying covariates

The source separates two kinds, and the kind decides the method. An internal covariate has a path affected by survival status: it is the output of a stochastic process of the individual and is observed only while the person is alive and uncensored. Repeated clinical measurements, such as C-reactive protein in sepsis, are the example given. An external covariate has a path that failure does not affect, for example age during a long trial or airborne pollution when the outcome is asthma attacks. Zhang et al. report that time-dependent Cox models are “more appropriate for external covariates”, and name joint modelling of longitudinal and survival data as the other main approach for internal ones.

Type Path affected by the event? Example in the source Usual approach
Internal Yes; observed only while the person survives uncensored C-reactive protein in sepsis Joint modelling of longitudinal and survival data
External No Age in a long trial; airborne pollution and asthma attacks Extended (time-dependent) Cox model

Formula for a Cox model with a time-varying covariate

The extended Cox model replaces the fixed covariate with its value at time t:

h(t | X(t)) = h0(t) · exp(β · X(t))

  • h(t | X(t)): the hazard (instantaneous event rate) at time t for a person whose covariate value at that time is X(t).
  • h0(t): the baseline hazard, left unspecified in a Cox model.
  • X(t): the covariate’s value at time t. For a switch such as starting treatment, X(t) = 0 before the switch and 1 after it.
  • β: the log hazard ratio for a one-unit difference in X(t); exp(β) is the hazard ratio comparing people with different current values at the same time.

Because X(t) differs from person to person at each time, the hazard ratio between two specific people is no longer constant over time. Zhang et al. note that under the extended model the hazard ratio is non-constant, even though β is a single number. Fisher and Lin add that these models usually cannot be used to predict a survival curve, and that the estimated event probability over time is not related to the hazard function in the usual way.

Worked example with the arithmetic shown

This is an illustrative composite with invented numbers, built only to show the mechanics; it is not a study. Eight people are followed for up to 12 time units. Four of them (ids 1, 3, 5, 7) start a treatment part-way through follow-up, and the other four never do. The covariate z is 0 before the start and 1 after it. The “event” is the outcome of interest; a person with no event is censored at the end time.

Step 1: put the data in start/stop (long) format

Each row is one interval, with start exclusive and stop inclusive. A person who switches contributes two rows; a person who does not switch contributes one. The same layout is described in the lifelines documentation, with columns id, start, stop and event.

id start stop z event
1 0 3 0 0
1 3 8 1 1
2 0 5 0 1
3 0 2 0 0
3 2 10 1 0
4 0 4 0 1
5 0 6 0 0
5 6 12 1 1
6 0 9 0 0
7 0 1 0 0
7 1 7 1 1
8 0 11 0 1

Step 2: build the risk set at each event time

The Cox partial likelihood compares, at each event time, the person who had the event with everyone still at risk at that moment, using each person’s covariate value at that moment. There are six distinct event times (4, 5, 7, 8, 11, 12). At time 4, for example, all 8 people are at risk; ids 1, 3 and 7 have already started treatment (z = 1) and ids 2, 4, 5, 6 and 8 have not, so 3 are exposed and 5 are not. The person with the event, id 4, has z = 0. The full risk-set counts for all six event times are in the data table below this section.

Step 3: write the log partial likelihood and solve for β

With n1 at risk and exposed and n0 at risk and unexposed at event time t, each event contributes β·z − ln(n0 + n1·eβ), where z is the event person’s covariate value at t. Summing over the six event times, with three events occurring in exposed people (times 7, 8 and 12):

ℓ(β) = 3β − [ln(5 + 3eβ) + ln(4 + 3eβ) + ln(2 + 4eβ) + ln(2 + 3eβ) + ln(1 + eβ) + ln(eβ)]

At β = 0 the bracket is ln(8) + ln(7) + ln(6) + ln(5) + ln(2) + ln(1) = ln(3,360) = 8.120, so ℓ(0) = −8.120. Newton-Raphson iterations on this function converge to β̂ = −0.484, where ℓ(β̂) = −7.983. The hazard ratio is exp(−0.484) = 0.62. The standard error from the observed information is 0.934, so the 95% confidence interval for the hazard ratio is exp(−0.484 ± 1.96 × 0.934) = 0.10 to 3.85. The Wald statistic is z = −0.484 / 0.934 = −0.52, giving p = .60. The likelihood-ratio statistic is 2 × (−7.983 − (−8.120)) = 0.27 on 1 degree of freedom, also p = .60. The Python code below reproduces these numbers.

Step 4: compare with the baseline-only shortcut

Coding the same people with a fixed “ever treated” flag (z = 1 from time 0 for ids 1, 3, 5 and 7) and fitting an ordinary Cox model gives a hazard ratio of 0.50 instead of 0.62 on these data. The fixed flag credits person-time before the switch to the treated group, which is the mechanism behind immortal time bias. The size of the gap here is specific to this tiny invented data set and says nothing about how large the bias is in general.

How to interpret the result

The estimate answers one question: at any given time, how does the hazard of someone whose covariate currently has one value compare with someone whose covariate currently has another? For the binary example, exp(β) compares exposed with not yet exposed people at the same time. See the guide on how to interpret a hazard ratio for the general reading rules.

Result Reading for a binary time-varying covariate
exp(β) below 1 Lower current hazard while exposed than while unexposed, at the same time point
exp(β) = 1 No difference in current hazard
exp(β) above 1 Higher current hazard while exposed than while unexposed
Confidence interval includes 1 The data are compatible with no difference, as in the example above (0.10 to 3.85)

The example estimate of 0.62 therefore reads as a lower hazard after starting treatment, but with eight people and six events the interval is wide and uninformative. That is a property of the toy data, not a finding.

Assumptions and common mistakes

  • Using the baseline value only. Zhang et al. point out that this fails to consider the outcome as a function of the covariate’s change over time.
  • Coding “ever exposed” as fixed. This moves exposed person-time that happened before the exposure into the exposed group; this is the mechanism behind immortal time bias.
  • Treating an internal covariate like an external one. For covariates that are affected by the event process or exist only while the person is alive, Fisher and Lin warn that the relationship between outcome and variable over time can lead to bias unless it is well understood.
  • Expecting survival curves. The extended model cannot usually predict a survival curve, and lifelines states that prediction in a time-varying setting is not trivial.
  • Using a state value where an accumulated amount is meant. lifelines provides a cumulative_sum option for incremental quantities such as dose, and a delay option for reverse causation, in its add_covariate_to_timeline helper.
  • Time-varying confounding. When a time-varying covariate is also a confounder affected by earlier treatment, the standard extended Cox model is not the whole answer; see marginal structural models and g-computation.

How to report a time-varying covariate (APA style)

State that the covariate was modelled as time-varying, how it was coded, the number of participants and events, and the hazard ratio with its interval. An example for the worked data above:

Treatment start was entered as a time-varying covariate in a Cox proportional hazards model using counting-process (start/stop) data. Among 8 participants with 6 events, the hazard ratio for treated versus not yet treated was 0.62, 95% CI [0.10, 3.85], z = −0.52, p = .60.

How to calculate it in Excel, R or Python

Time-varying covariate in survival analysis with Python (lifelines)

import pandas as pd
from lifelines import CoxTimeVaryingFitter

df = pd.DataFrame(
    [(1,0,3,0,0),(1,3,8,1,1),(2,0,5,0,1),(3,0,2,0,0),(3,2,10,1,0),
     (4,0,4,0,1),(5,0,6,0,0),(5,6,12,1,1),(6,0,9,0,0),
     (7,0,1,0,0),(7,1,7,1,1),(8,0,11,0,1)],
    columns=['id','start','stop','z','event'])

ctv = CoxTimeVaryingFitter()
ctv.fit(df, id_col='id', event_col='event', start_col='start', stop_col='stop')
ctv.print_summary()   # coef -0.48, exp(coef) 0.62

Time-varying covariate in R

With the same long-format data frame saved as df, the survival package fits the counting-process form directly. The Zhang et al. article uses the same reshaped layout with coxph(), and its output gives a single hazard ratio for the time-varying variable:

library(survival)
fit = coxph(Surv(start, stop, event) ~ z, data = df)
summary(fit)   # exp(coef) for z should match the Python result

Time-varying covariate in Excel

Excel has no built-in Cox regression, so use it for the data set-up and the risk-set counts, then fit the model in R or Python. With start in column B, stop in column C and z in column D of the long table, the number at risk and exposed at event time t (held in cell G2) is:

Use COUNTIFS with three criteria: start less than t, stop at least t, and z equal to 1.

Replace the final 1 with 0 for the unexposed count. For t = 4 this returns 3 and 5, matching Step 2. SPSS and Stata users can build the same long table and then use their own survival procedures; the data layout, not the package, is what makes the covariate time-varying.

Time-varying covariate calculator

There is no single formula to plug numbers into: the estimate comes from maximising the partial likelihood, as in Step 3. The practical “calculator” is therefore the long-format table plus a Cox routine such as the R or Python code above.

Sources

Data: Risk sets at each event time in the worked time-varying covariate example

Illustrative composite of eight people with start/stop follow-up data, constructed for this page (not a real study). For each of the six event times the table gives the number at risk, the number at risk with the covariate currently 1 (treated) or 0, the covariate value of the person with the event, and the score contribution at beta = 0 (event person's covariate minus the expected value n1/n). The long-format layout follows the lifelines documentation; the partial-likelihood terms follow the extended Cox model in Zhang et al. (2018).

Risk sets at each event time in the worked time-varying covariate example
Event timeEvent person idNumber at riskAt risk, z = 1At risk, z = 0Event person's zScore contribution at beta = 0
448350-0.375
527340-0.4286
7764210.3333
8153210.4
1182110-0.5
12511010

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Time-Varying Covariate: Definition, Long-Format Data and a Cox Example

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →