---
title: "Using cox.rvph"
author: "Hamin Kim"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using cox.rvph}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Introduction

The `cox.rvph` package provides two approaches for handling violations of
the proportional hazards assumption in Cox proportional hazards models:

1. a stepwise approach, and
2. a time-varying coefficient approach.

This vignette illustrates the basic workflow for both methods.

```{r setup}
library(cox.rvph)
library(survival)
```

## Stepwise approach

The stepwise approach partitions the follow-up timeline into discrete intervals using one or more split points and allows the effect of the selected covariate to remain constant within each interval.

The following example uses the `psych` data from the `KMsurv` package.

```{r step-example}
if (requireNamespace("KMsurv", quietly = TRUE)) {

  data("psych", package = "KMsurv")
  psych$sex <- factor(psych$sex)

  fit_step <- cox.rvph(
    data = psych,
    time = "time",
    event = "death",
    covariate = "age",
    adjust_vars = "sex",
    method = "step",
    verbose = FALSE
  )

  print(fit_step)
  summary(fit_step)
}
```

The returned object contains the selected number of time intervals,
estimated split-point locations, the proportional hazards test result,
and the fitted Cox model.

## Time-varying coefficient approach

The time-varying coefficient approach compares candidate time functions
and selects the specification with the smallest AIC.

The following example uses the `pbc` data from the `survival` package.

```{r timev-example}
data("pbc", package = "survival")

pbc$status2 <- ifelse(pbc$status == 2, 1, 0)
pbc$ascites <- factor(pbc$ascites)

fit_timev <- cox.rvph(
  data = pbc,
  time = "time",
  event = "status2",
  covariate = "bili",
  adjust_vars = c("ascites", "edema", "protime"),
  method = "timev",
  verbose = FALSE
)

print(fit_timev)
summary(fit_timev)
```

The returned object contains the selected time function,
AIC values for the candidate time-function specifications,
and the fitted Cox model.

## Summary

The `cox.rvph` package provides automated workflows for addressing
violations of the proportional hazards assumption using either a
stepwise approach or a time-varying coefficient approach.