## ----setup, include=FALSE------------------------------------------------ knitr::opts_chunk$set(echo = TRUE) options(knitr.duplicate.label = 'allow') ## ----kidney_load--------------------------------------------------------- library(KMsurv) library(survival) data(kidney,package="KMsurv") head(kidney) ## ----coxphfit------------------------------------------------------------ ?coxph fit <- coxph(Surv(time,delta)~type,data=kidney,ties="breslow") fit ## ----coxphcheck, eval=TRUE----------------------------------------------- ## fit survival functions using fleming-harrington ## this is same as Nelson-Aalen for cumulative hazard fit <- survfit(Surv(time,delta)~type,data=kidney, type="fleming-harrington") ## separate times and survival functions for two groups ti1 <- fit$time[1:fit$strata[1]] ti2 <- fit$time[(fit$strata[1]+1):length(fit$time)] s1 <- fit$surv[1:fit$strata[1]] s2 <- fit$surv[(fit$strata[1]+1):length(fit$time)] ## interpolate so survival functions ## evaluated on same grid lg <- max(min(ti1),min(ti2)) rg <- min(max(ti1),max(ti2)) g <- seq(lg,rg,length.out=100) s1g <- approx(ti1,s1,xout=g,method="constant",f=0) s2g <- approx(ti2,s2,xout=g,method="constant",f=0) ## survival functions to cumulative hazards g1H <- -log(s1g$y) g2H <- -log(s2g$y) ## log hazard ratio plot(g,log(g2H/g1H),type='l',xlab="Time", ylab="log(H(t|Z=1)/H(t|Z=0))", main="Figure 8.1 in Textbook") ## ----coxph_tests--------------------------------------------------------- fit <- coxph(Surv(time,delta)~type,data=kidney,ties="breslow") fit str(fit) ## ----coxph_wald---------------------------------------------------------- ## wald test statistic coef(fit)^2/fit$var ## wald test statistic fit$wald.test ## wald p-value, similar to likelihood ratio p-value ## which can be see by print(fit) pchisq(fit$wald.test,df=1,lower.tail=FALSE) ## ----larynx_stage-------------------------------------------------------- data(larynx) head(larynx) fit <- coxph(Surv(time,delta)~as.factor(stage)+age, data=larynx,ties="breslow") fit ## ----larynx_stage_global_wald-------------------------------------------- fit$wald.test fit$var coef(fit) co_mat <- matrix(coef(fit),ncol=1) t(co_mat)%*%solve(fit$var)%*%co_mat pchisq(fit$wald.test,df=4,lower.tail=FALSE) ## ----larynx_stage_local_wald--------------------------------------------- co_mat <- co_mat[1:3] var_mat <- fit$var[1:3,1:3] tw <- t(co_mat)%*%solve(var_mat)%*%co_mat tw co_mat var_mat pchisq(tw,df=3,lower.tail=FALSE) dim(larynx) ## ----makedotRfile, echo=FALSE, include=FALSE----------------------------- ## automatrically generates .R file when running knitr knitr::purl("02coxph.Rmd")