开始使用免费开始使用

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.

本练习是课程的一部分

Life Insurance Products Valuation in R

查看课程

练习说明

  • 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.

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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")
编辑并运行代码