#=====> 10. Cox PH model, time-dependent covariates <=====#
data(relapse)
relapse
attach(relapse)
N <- dim(relapse)[1]
t1 <- rep(0, N+sum(!is.na(inter))) # Initialize start times at 0
t2 <- rep(NA, length(t1)) # The end times for each record
e <- rep(NA, length(t1)) # Was the event censored?
g <- rep(NA, length(t1)) # Gender
PI <- rep(FALSE, length(t1)) # Initialize intervention at FALSE
R <- 1 # Row of new record
for(ii in 1:dim(relapse)[1]){
if(is.na(inter[ii])){ # no intervention, copy survival record
t2[R] <- event[ii]
e[R] <- delta[ii]
g[R] <- gender[ii]
R <- R+1
} else { # intervention, split records
g[R+0:1] <- gender[ii] # gender is same for each time
e[R] <- 0 # no relapse observed pre-intervention
e[R+1] <- delta[ii] # relapse occur post-intervention?
PI[R+1] <- TRUE # Intervention covariate, post-intervention
t2[R] <- inter[ii]-1 # End of pre-intervention
t1[R+1] <- inter[ii]-1 # Start of post-intervention
t2[R+1] <- event[ii] # End of post-intervention
R <- R+2 # Two records added
}
}
mySurv <- Surv(t1, t2, e)
coxphFit <- coxph(mySurv ~ g + PI)
detach(relapse)
Run the code above in your browser using DataLab