# Introduction to the vital package

#### Rob J Hyndman

The goal of vital is to allow analysis of demographic data using tidy tools. It works with other tidyverse packages such as dplyr and ggplot2. It also works with the tidyverts packages, tsibble and fable.

    library(vital)
    library(tsibble)
    library(dplyr)
    library(ggplot2)

## vital objects

The basic data object is a `vital`, which is a time-indexed tibble that contains vital statistics such as births, deaths, population counts, and mortality and fertility rates.

We will use Norwegian data in the following examples. First, let’s remove the “Total” Sex category and collapse the upper ages into a final age group of 100+.

    nor <- norway_mortality |>
      filter(Sex != "Total") |>
      collapse_ages(max_age = 100)
    nor
    #> # A vital: 25,048 x 7 [1Y]
    #> # Key:     Age x Sex [101 x 2]
    #>     Year   Age OpenInterval Sex    Population Deaths Mortality
    #>    <int> <int> <lgl>        <chr>       <dbl>  <dbl>     <dbl>
    #>  1  1900     0 FALSE        Female      30070 2376.    0.0778
    #>  2  1900     1 FALSE        Female      28960  842     0.0290
    #>  3  1900     2 FALSE        Female      28043  348     0.0123
    #>  4  1900     3 FALSE        Female      27019  216.    0.00786
    #>  5  1900     4 FALSE        Female      26854  168.    0.00624
    #>  6  1900     5 FALSE        Female      25569  140.    0.00538
    #>  7  1900     6 FALSE        Female      25534  108.    0.00422
    #>  8  1900     7 FALSE        Female      24314   93.5   0.00376
    #>  9  1900     8 FALSE        Female      24979   93.5   0.00380
    #> 10  1900     9 FALSE        Female      24428   90     0.00365
    #> # ℹ 25,038 more rows

This example contains data from 1900 to 2023. There are 101 age groups and 2 Sex categories. A vital must have a time “index” variable, and optionally other categorical variables known as “key” variables. Each row must have a unique combination of the index and key variables. Some columns are “vital” variables, such as “Age” and “Sex”.

We can use functions to see which variables are index, key or vital:

    index_var(nor)
    key_vars(nor)
    vital_vars(nor)

## Plots

There are `autoplot()` functions for plotting `vital` objects. These produce rainbow plots (Hyndman and Shang 2010) where each line represents data for one year, and the variable is plotted against age.

    nor |>
      autoplot(Mortality) +
      scale_y_log10()

We can use standard ggplot functions to modify the plot as desired. For example, here are population pyramids for all years.

    nor |>
      mutate(Population = if_else(Sex == "Female", -Population, Population)) |>
      autoplot(Population) +
      coord_flip() +
      facet_grid(. ~ Sex, scales = "free_x")

## Life tables and life expectancy

Life tables (Chiang 1984) can be produced using the `life_table()` function. It will produce life tables for each unique combination of the index and key variables other than age.

    # Life tables for males and females in Norway in 2000
    nor |>
      filter(Year == 2000) |>
      life_table()

Life expectancy (\(e_x\) with \(x=0\) by default) is computed using `life_expectancy()`:

    # Life expectancy for males and females in Norway
    nor |>
      life_expectancy() |>
      ggplot(aes(x = Year, y = ex, color = Sex)) +
      geom_line()

## Smoothing

Several smoothing functions are provided: `smooth_spline()`, `smooth_mortality()`, `smooth_fertility()`, and `smooth_loess()`, each smoothing across the age variable for each year. The methods used in `smooth_mortality()` and `smooth_fertility()` are described in Hyndman and Ullah (2007).

    # Smoothed data
    nor |>
      filter(Year == 1967) |>
      smooth_mortality(Mortality) |>
      autoplot(Mortality) +
      geom_line(aes(y = .smooth), col = "#0072B2") +
      ylab("Mortality rate") +
      scale_y_log10()

## Lee-Carter models

Lee-Carter models (Lee and Carter 1992) are estimated using the `LC()` function which must be called within a `model()` function:

    # Lee-Carter model
    lc <- nor |>
      model(lee_carter = LC(log(Mortality)))
    lc

Models are fitted for all combinations of key variables excluding age. To see the details for a specific model, use the `report()` function.

    lc |>
      filter(Sex == "Female") |>
      report()

The results can be plotted.

    autoplot(lc)

The components can be extracted.

    age_components(lc)
    time_components(lc)

Forecasts are obtained using the `forecast()` function

    # Forecasts from Lee-Carter model
    lc |>
      forecast(h = 20)

The forecasts are returned as a distribution column (here transformed normal because of the log transformation used in the model). The `.mean` column gives the point forecasts equal to the mean of the distribution column.

## Functional data models

Functional data models (Hyndman and Ullah 2007) can be estimated in a similar way to Lee-Carter models, but with an additional smoothing step, then modelling with `LC` replaced by `FDM`.

    # FDM model
    fdm <- nor |>
      smooth_mortality(Mortality) |>
      model(hu = FDM(log(.smooth)))
    fc_fdm <- fdm |>
      forecast(h = 20)
    autoplot(fc_fdm) +
      scale_y_log10()

Functional data models have multiple principal components, rather than the single factor used in Lee-Carter models.

    fdm |>
      autoplot(show_order = 3)

By default, six factors are estimated using `FDM()`. Here we have chosen to plot only the first three.

The components can be extracted.

    age_components(fdm)
    time_components(fdm)

## Coherent functional data models

A coherent functional data model (Hyndman et al. 2013), is obtained by first computing the sex-products and sex-ratios of the smoothed mortality data. Then a functional data model is fitted to the smoothed data, forecasts are obtained, and the product/ratio transformation is reversed. The following code shows the steps.

    fdm_coherent <- nor |>
      smooth_mortality(Mortality) |>
      make_pr(.smooth) |>
      model(hby = FDM(log(.smooth), coherent = TRUE))
    fc_coherent <- fdm_coherent |>
      forecast(h = 20) |>
      undo_pr(.smooth)
    fc_coherent

Here, `make_pr()` makes the product-ratios, while `undo_pr()` undoes them.

The argument `coherent = TRUE` in `FDM()` ensures that the ARIMA models fitted to the coefficients are stationary when applied to the sex-ratios.

## References

Chiang, Chin Long. 1984. The Life Table and Its Applications. Robert E Krieger Publishing Company.
Hyndman, Rob J, Heather Booth, and Farah Yasmeen. 2013. “Coherent Mortality Forecasting: The Product-Ratio Method with Functional Time Series Models.” Demography 50 (1): 261–83. https://robjhyndman.com/publications/coherentfdm/.
Hyndman, Rob J, and Han Lin Shang. 2010. “Rainbow Plots, Bagplots, and Boxplots for Functional Data.” Journal of Computational and Graphical Statistics 19 (1): 29–45. https://robjhyndman.com/publications/rainbow-fda/.
Hyndman, Rob J, and Md Shahid Ullah. 2007. “Robust Forecasting of Mortality and Fertility Rates: A Functional Data Approach.” Computational Statistics & Data Analysis 51 (10): 4942–56. https://robjhyndman.com/publications/funcfor/.
Lee, Ronald D, and Lawrence R Carter. 1992. “Modeling and Forecasting US Mortality.” Journal of the American Statistical Association 87 (419): 659–71.