## EXAMPLE 1:
library(survival)
dat.df01 <- lung
dat.df01$status <- ifelse(dat.df01$status == 1, 0, dat.df01$status)
dat.df01$status <- ifelse(dat.df01$status == 2, 1, dat.df01$status)
dat.df01$sex <- factor(dat.df01$sex, levels = c(1,2), 
   labels = c("Male","Female"))
lung.km01 <- survfit(Surv(time = time, event = status) ~ 1, data = dat.df01)
lung.haz01 <- epi.insthaz(survfit.obj = lung.km01, conf.level = 0.95)
lung.shaz01 <- data.frame(
  time = lowess(lung.haz01$time, lung.haz01$hlow, f = 0.20)$x,
  hest =  lowess(lung.haz01$time, lung.haz01$hest, f = 0.20)$y,
  hlow =  lowess(lung.haz01$time, lung.haz01$hlow, f = 0.20)$y,
  hupp =  lowess(lung.haz01$time, lung.haz01$hupp, f = 0.20)$y)
plot(x = lung.haz01$time, y = lung.haz01$hest, xlab = "Time (days)", 
   ylab = "Daily probability of event", type = "s", 
   col = "grey", ylim = c(0, 0.05))
lines(x = lung.shaz01$time, y = lung.shaz01$hest, 
      lty = 1, lwd = 2, col = "black")
lines(x = lung.shaz01$time, y = lung.shaz01$hlow, 
      lty = 2, lwd = 1, col = "black")
lines(x = lung.shaz01$time, y = lung.shaz01$hupp, 
      lty = 2, lwd = 1, col = "black")
if (FALSE) { 
library(ggplot2)
ggplot() +
  theme_bw() +
  geom_step(data = lung.haz01, aes(x = time, y = hest), colour = "grey") + 
  geom_smooth(data = lung.haz01, aes(x = time, y = hest), method = "loess", 
     colour = "black", size = 0.75, linetype = "solid", 
     se = FALSE, span = 0.20) +
  geom_smooth(data = lung.haz01, aes(x = time, y = hlow), method = "loess", 
     colour = "black", size = 0.5, linetype = "dashed", 
     se = FALSE, span = 0.20) +
  geom_smooth(data = lung.haz01, aes(x = time, y = hupp), method = "loess", 
     colour = "black", size = 0.5, linetype = "dashed", 
     se = FALSE, span = 0.20) +
  scale_x_continuous(limits = c(0,1000), name = "Time (days)") +
  scale_y_continuous(limits = c(0,0.05), name = "Daily probability of event") 
}
## EXAMPLE 2:
## Now stratify by gender:
lung.km02 <- survfit(Surv(time = time, event = status) ~ sex, data = dat.df01)
lung.haz02 <- epi.insthaz(survfit.obj = lung.km02, conf.level = 0.95)
if (FALSE) { 
library(ggplot2)
ggplot() +
  theme_bw() +
  geom_step(data = lung.haz02, aes(x = time, y = hest), colour = "grey") + 
  facet_grid(strata ~ .) +
  geom_smooth(data = lung.haz02, aes(x = time, y = hest), method = "loess", 
     colour = "black", size = 0.75, linetype = "solid", 
     se = FALSE, span = 0.20) +
  geom_smooth(data = lung.haz02, aes(x = time, y = hlow), method = "loess", 
     colour = "black", size = 0.5, linetype = "dashed", 
     se = FALSE, span = 0.20) +
  geom_smooth(data = lung.haz02, aes(x = time, y = hupp), method = "loess", 
     colour = "black", size = 0.5, linetype = "dashed", 
     se = FALSE, span = 0.20) +
  scale_x_continuous(limits = c(0,1000), name = "Time (days)") +
  scale_y_continuous(limits = c(0,0.05), name = "Daily probability of event")
}
Run the code above in your browser using DataLab