I am wondering if anyone has used the Cox proportional-hazards regression model to see if previous exposure to a variable is correlated with an event?

I am using the "coxph" function in the survival package in R, and following the Rossi example on Cox Proportional-Hazards Regression for Survival Data in R.

I am interested in the correlation between week of arrest (3rd column) and employment status (last column) in the image below. However I'd like to extend the employment window in reverse, and ask if the person has been employed at a given previous visit.

Does anyone have any ideas or suggestions, in terms of R functions or how to re-organize the data? Thanks!

Rossi.2 sample data on https://socserv.socsci.mcmaster.ca/jfox/Books/Companion/appendix/Appendix-Cox-Regression.pdf

  • $\begingroup$ Dear @YuvalSp, thanks for your answer! I ended up "pushing" exposure by n lags by modifying my matrix (e.g. if n = 30, then exposure at day 1 becomes exposure at day 30, while keeping the day of event identical, in order to detect any difference with "lag"). Thanks! :) -Joyce $\endgroup$ Commented Dec 4, 2016 at 4:40

2 Answers 2


You are seeking to lag a time-dependent covariate. In the link you supplied the author gives a function he created called unfold with explanation on usage starting at p.9 in the linked article. You can use it, as he does, to lag a variable (see p.11 there).

However, as far as I can tell this is not a very generic function and is only good when unfolding a wide to a long format of data. if your data is already long, e.g. (example from Therneau's great vignette on time-dependent covariates and coefficients):

subject time1 time2 status age creatinine . . .
1       0     15    0      25  1.3
1       15    46    0      25  1.5
1       46    73    0      25  1.4
1       73    100   1      25  1.6

than you can write a small piece of code to do the lagging for you (note: I am not a very good R programmer yet. There are better ways of doing it I'm sure, but this works):

# @a is the dataset, @lag_var is the new variable to be 1 spell lagged, 
# @var_to_lag is the base variable
# the 0s and 1s in the lag var is just if it is in a 0 or 1 format. 
# could be TRUE or FALSE or whatever..
# @id is the unique identifier for the multiple rows of each person 

a$lag_var <- 0

for (i in 1:(nrow(a)-1)) {
     if (a[i,]$id == a[i+1,]$id & a[i+1,]$var_to_lag==1) {
         a[i,]$lag_var <- 1

Note that the code above will make an 'exposure' vanish is it can't be lagged (meaning that the person has only one period for some reason).


I was looking for an equivalent of the "NLAG" option in SAS - so I guess the simplest solution would be to generate a new column for the lagged variable.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.