# Анализ выживаемости

```{r}
library(survival)
library(KMsurv)
```

\[
  \left(
    C \hat\beta - d
  \right)^T
  
  \left(
    C I^{-1} C^T
  \right)^{-1}
  
  \left(
    C \hat\beta - d
  \right) \sim \chi^2_r
\]

\[
  \hat\beta^T
  I
  \hat\beta \sim \chi^2_4
\]

```{r}
data(burn)
attach(burn)
surv <- Surv(T1, D1)
fit <- coxph(surv ~ Z1 + as.factor(Z11))
summary(fit)

fit$coefficients
fit$var   # I^{-1}

beta <- matrix(fit$coefficients, ncol = 1)
I <- solve(fit$var)

(test <- t(beta) %*% I %*% beta)
1 - pchisq(test, df = 4)
detach(burn)
```

## Зависимость от времени

```{r}
relapse <- read.csv("relapse.csv")
n <- dim(relapse)[1] + sum(!is.na(relapse$inter))
t1 <- c() # start times
t2 <- c() # end time
d <- c()
g <- c()
inter <- c()
for (i in 1:dim(relapse)[1]) {
  if (!is.na(relapse$inter[i])) {
    # Had intervervention => 2 data row
    interTime <- relapse$inter[i]
    eventTime <- relapse$event[i]
    if (eventTime == interTime) {
      eventTime <- eventTime + 1
    }
    t1 <- c(t1, 0, interTime)
    t2 <- c(t2, interTime, eventTime)
    d <- c(d, 0, relapse$delta[i])
    g <- c(g, relapse$gender[i], relapse$gender[i])
    inter <- c(inter, F, T)
  }
  else {
    # Not intervention -> 1 data row
    t1 <- c(t1, 0)
    t2 <- c(t2, relapse$event[i])
    d <- c(d, relapse$delta[i])
    g <- c(g, relapse$gender[i])
    inter <- c(inter, F)
  }
}
surv <- Surv(t1, t2, d)
fit <- coxph(surv ~ g + inter)
summary(fit)

fit.2 <- coxph(surv ~ inter)
summary(fit.2)
```


