---
title: "Biostatistics III in R"
author:
- Code by Annika Tillander, Andreas Karlsson and Mark Clements
output:
  prettydoc::html_pretty:
    theme: cayman
    highlight: github
filters:
  - webr
---

# Exercise 1: Life tables and Kaplan-Meier estimates of survival #

```{webr-r}
#| cache: false
#| message: false
#| echo: false
library('knitr')
read_chunk('../q1.R')
opts_chunk$set(cache=FALSE, fig.width=7, fig.height=6)
options(width=90)
```

## (a) Hand calculation: Life table and Kaplan-Meier estimates of survival ##

The results are contained in an [Excel file](exercise1.xls) and are also shown in the R
    output below.

## (b) Using R to validate the hand calculations done in part 1 (a) ##

First, load the `biostat3` library:

```{webr-r}
#| echo: true
library(biostat3)
library(survminer)
```

Following are the life table estimates. Note that in the lectures,
    when we estimated all-cause survival, there were 8 deaths in the
    first interval. One of these died of a cause other than cancer so in
    the cause-specific survival analysis we see that there are 7
    ‘deaths’ and 1 censoring (Stata uses the term ‘lost’ for lost
    to follow-up) in the first interval.

```{webr-r}
print(lifetab2(Surv(floor(surv_yy), status == "Dead: cancer")~1, colon_sample, breaks=0:10), digits=2)
```

Following is a table of Kaplan-Meier estimates. Although it’s not
    clear from the table, the person censored (lost) at time 2 was at
    risk when the other person dies at time 2. On the following is
    a graph of the survival function.

```{webr-r}
mfit <- survfit(Surv(surv_mm/12, status == "Dead: cancer") ~ 1, data = colon_sample) # make Kaplan-Meier estimates
summary(mfit)                                                  # print Kaplan-Meier table
plot(mfit,                                                     # plot Kaplan-Meier curve
     ylab="S(t)",
     xlab="Time since diagnosis (years)",
     main = "Kaplan−Meier estimates of cause−specific survival")

ggsurvplot(mfit,                                                     # plot Kaplan-Meier curve
     ylab="S(t)",
     xlab="Time since diagnosis (years)",
     main = "Kaplan−Meier estimates of cause−specific survival",
     risk.table = TRUE,
     conf.int = TRUE,
     ggtheme = theme_minimal())
```

