Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. # load libraries --------------------------------------------------------------------
  2.  
  3. library(survival)
  4. library(data.table)
  5. library(magrittr)
  6. library(ggplot2)
  7.  
  8. options(stringsAsFactors = FALSE, scipen = 10)
  9.  
  10.  
  11. # load data (from package) ----------------------------------------------------------
  12.  
  13. cancer2 <-
  14. copy(cancer) %>%
  15. setDT() # dataset stored in the survival package for testing
  16. cancer3 <- cancer2[complete.cases(cancer2)] # taking complete cases to avoid NA observations on fitted model
  17.  
  18.  
  19. # run cox model ---------------------------------------------------------------------
  20.  
  21. x <- coxph(Surv(time, status) ~ age + factor(sex) + factor(ph.ecog), data = cancer3) # cox model
  22.  
  23.  
  24.  
  25. # function to generate mean survival by factor --------------------------------------
  26.  
  27. adj_curves <- function(dt, obj, fac){
  28. if(!is.factor(dt[[fac]])) {
  29. dt[[fac]] <- factor(dt[[fac]])
  30. }
  31. groups <- levels(dt[[fac]])
  32. pred <- survfit(obj, dt)
  33. timepoints <- c(0, pred$time)
  34. timenames <- paste0("time", timepoints)
  35. adj_surv <- as.data.frame(t(pred$surv))
  36. adj_surv <- cbind(time0 = 1, adj_surv)
  37. names(adj_surv) <- timenames
  38. dt <- cbind(dt, adj_surv)
  39. dt2 <- dt[, lapply(.SD, mean), .SDcols = timenames, by = fac]
  40. graph <- as.data.table(cbind(timepoints, t(dt2[, -1])))
  41. names(graph) <- c("Time", groups)
  42. graph <- melt.data.table(data = graph, id.vars = "Time", variable.name = fac, value.name = "Survival")
  43. return(graph)
  44. }
  45.  
  46.  
  47. # run function and plot data --------------------------------------------------------
  48.  
  49. gr <- adj_curves(cancer3, x, "sex")
  50.  
  51. ggplot(gr, aes(x = Time, y = Survival, color = sex)) +
  52. geom_step() +
  53. scale_y_continuous(limits = c(0, 1)) +
  54. theme_bw()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement