Get startedGet started for free

Plotting life expectancies by age

Cynthia decides to visualize the life expectancy as a function of age. Can you guide Cynthia on how to construct such a graph?

To do this efficiently in R, you should first write a function which computes the curtate life expectancy for a given age and life table. Then, you can apply this function over all ages in the life table. Using sapply() (docs) the output is simplified to the most elementary data structure possible.

The preloaded life_table object contains the 1999 period life table for females in Belgium.

This exercise is part of the course

Life Insurance Products Valuation in R

View Course

Exercise instructions

  • Complete the code defining the function curtate_future_lifetime().
  • Create a vector ages by extracting the age column from life_table.
  • Use sapply() with arguments ages, curtate_future_lifetime, and life_table to compute the curtate life expectancy at all ages in the life table.
  • Plot future_lifetimes versus ages.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Function to compute the curtate expected future lifetime for a given age and life table
curtate_future_lifetime <- function(age, life_table) {
  px <- ___
  kpx <- ___(px[(___):length(px)])
  ___(___)
}

# Vector of ages
ages <- ___

# Curtate future lifetimes for all ages
future_lifetimes <- ___(___, ___, ___)

# Future lifetime by age
plot(___, ___, type = 'l', lwd = 2, col = "green", xlab = "Age x", ylab = "Future lifetime", main = "Future lifetime by age")
Edit and Run Code