开始使用免费开始使用

按年龄绘制预期寿命

Cynthia 想把预期寿命作为年龄的函数进行可视化。您能指导她如何构建这样的图吗?

要在 R 中高效完成此事,您应先编写一个函数,用于在给定年龄和生命表下计算截尾预期寿命(curtate life expectancy)。然后,您可以把该函数应用到生命表中的所有年龄。使用 sapply()文档)可以将输出简化为尽可能基础的数据结构。

预加载的 life_table 对象包含比利时女性在 1999 年的期间生命表。

本练习是课程的一部分

用 R 评估人寿保险产品

查看课程

练习说明

  • 补全定义函数 curtate_future_lifetime() 的代码。
  • 通过提取 life_tableage 列创建向量 ages
  • 使用 sapply(),将 agescurtate_future_lifetimelife_table 作为参数,计算生命表中各年龄的截尾预期寿命。
  • 绘制 future_lifetimesages 的关系图。

交互式实操练习

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

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