依年齡繪製期望壽命
Cynthia 想把期望壽命視為年齡的函式來視覺化。你能引導 Cynthia 如何建立這樣的圖表嗎?
為了在 R 中有效完成這件事,你應先撰寫一個函式,用來計算在給定年齡與生命表下的整數期望壽命(curtate life expectancy)。接著,你可以把這個函式套用到生命表中的所有年齡。使用 sapply()(文件)時,輸出會被簡化成最基本的資料結構。
已預先載入的 life_table 物件包含比利時女性在 1999 年的期間生命表。
本練習屬於課程
以 R 估值人壽保險商品
練習說明
- 完成定義函式
curtate_future_lifetime()的程式碼。 - 從
life_table中擷取age欄,建立向量ages。 - 使用
sapply(),以ages、curtate_future_lifetime與life_table作為引數,計算生命表中所有年齡的整數期望壽命。 - 繪製
future_lifetimes對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")