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
agesby extracting theagecolumn fromlife_table. - Use
sapply()with argumentsages,curtate_future_lifetime, andlife_tableto compute the curtate life expectancy at all ages in the life table. - Plot
future_lifetimesversusages.
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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")