Below are the solutions to these exercises on Survival Analysis Part-3.

############### # # # Exercise 1 # # # ############### library(survival) library(survminer) data("lung") lung$status <- as.factor(lung$status) # 1 Censored 2 Dead final_model <- coxph(Surv(time, status == 2) ~ sex + ph.karno + wt.loss + sex*ph.karno, data = lung) ############### # # # Exercise 2 # # # ############### marting_res <- residuals(final_model, type = "martingale") residual_df <- data.frame(index = 1:length(marting_res), martingale <- marting_res) ############### # # # Exercise 3 # # # ############### library(ggplot2) library(dplyr) residual_df %>% ggplot(aes(x = index, y = martingale)) + geom_point(alpha = 0.7, colour = "blue") + theme_bw()

############### # # # Exercise 4 # # # ############### residual_df$deviance <- residuals(final_model, type = "deviance") residual_df %>% ggplot(aes(x = index, y = deviance)) + geom_point(colour = "blue", alpha = 0.7) + theme_bw()

############### # # # Exercise 5 # # # ############### library(ggrepel) residual_df$linPred <- final_model$linear.predictors residual_df %>% ggplot(aes(x = linPred, y = deviance)) + geom_point(colour = "blue", alpha = 0.7) + geom_text_repel(data = subset(residual_df, linPred > 1), aes(linPred, deviance, label = index)) + labs(x = "Linear Predictor Value", y = "Deviance Residual") + theme_bw()

############### # # # Exercise 6 # # # ############### dfbetas <- data.frame(residuals(final_model, type = "dfbetas")) ############### # # # Exercise 7 # # # ############### terms <- c("Sex", "ph.Karno", "Weight Loss", "Sex * ph.Karno") par(mfrow = c(1,2)) for (i in 1:dim(dfbetas)[2]){ plot(dfbetas[, i], type = "h", col = "blue", ylab = paste("DFBetas for", terms[i])) }

par(mfrow = c(1,1)) ############### # # # Exercise 8 # # # ############### t <- cox.zph(final_model) ############### # # # Exercise 9 # # # ############### plot(t)

################ # # # Exercise 10 # # # ################ ggsurvplot(survfit(final_model), colour = "blue", ggtheme = theme_bw())

## Leave a Reply