library(survival)
# prepare a dataset with competing risk
lung1=lung[order(lung$time),]
lung1$status=lung1$status-1
lung1$status[1:50]=2
with(lung1, table(status))
lung1$status.1=ifelse(lung1$status==1,1,0)
lung1$status.2=ifelse(lung1$status==2,1,0)
lung1$status.a=ifelse(lung1$status==0,0,1)
lung1$wt=rep(1, nrow(lung1))
###############################################################################
# predictCompetingRisk2
t0=1000
formula.list=list(
Surv(time, status.1) ~ age,
Surv(time, status.2) ~ age
)
cif.2=pcr2(formula.list, lung1, t0)
fit=coxph(formula.list[[1]], lung1)
newdata=lung1
newdata$time=t0
coxpred = 1 - exp(-predict(fit, newdata=newdata, type="expected"))
plot(cif.2, coxpred)
# dealing with weights
lung1$wt=c(rep(2,50), rep(1, nrow(lung1)-50))
cif=predictCompetingRisk2(formula.list, lung1, t0, weights=lung1$wt)
###############################################################################
# predictCompetingRisk
t0=1000
form =Surv(time, status.1) ~ age
form.a=Surv(time, status.a) ~ age
cif=predictCompetingRisk(form, form.a, lung1, t0, newdata=lung1, weights=lung1$wt, stype=2,ctype=2)
# more validation code
# when there is no covariate and one cause, CIF = 1 - KM estimate of survival prob
lung1=lung[order(lung$time),]
lung1$status=lung1$status-1
with(lung1, table(status))
lung1$status.1=ifelse(lung1$status==1,1,0)
lung1$status.a=ifelse(lung1$status==0,0,1)
lung1$wt=rep(1, nrow(lung1))
# stype=2 is surv=prod limit
fitKM <- survfit(Surv(time, status.1) ~ 1, data=lung1, stype=1, ctype=2)
cbind(summary(fitKM)$cumhaz, exp(-summary(fitKM)$cumhaz), summary(fitKM)$surv)[1:2,]
#[1,] 0.004385965 0.9956236 0.9956140
#[2,] 0.017660474 0.9824946 0.9824561
cif=predictCompetingRisk(Surv(time, status.1) ~ 1, Surv(time, status.1) ~ 1, lung1, t0=11,
newdata=lung1[1,,drop=FALSE], weights=lung1$wt, stype=1, ctype=2)
cif # 0.01754386
1-cif # 0.9824561 = summary(fitKM)$surv at t=11
# when there are covariates and one cause, CIF and 1-exp(-H) are close to each other
# when H is small but not close when H is large
form =Surv(time, status.1) ~ age
form.a=Surv(time, status.a) ~ age
oldpar <- par(mfrow = c(1,2))
for (t0 in c(12,1000)) {
fit=coxph(form, lung1, weights=lung1$wt)
lung2=lung1; lung2$time=t0
r=predict(fit, type="expected", newdata=lung2)
message(head(basehaz(fit, centered=TRUE)))
cif=predictCompetingRisk(form, form.a, lung1, t0, newdata=lung1, weights=lung1$wt, stype=2,
ctype=2)
plot(cif, 1-exp(-r), xlab="Cumulative incidence function",
ylab="Expected number of events from predict.coxph", main=paste0("t0: ", t0))
abline(0,1)
message(head(cbind(cif, "1-exp(-r)"=1-exp(-r))))
}
par(oldpar)
Run the code above in your browser using DataLab