r语言 - 不确定如何修复'numerical expression has 41 elements: only the first used'警告



目前正在尝试编写函数来计算保证收益和储备/政策值,尽管在尝试绘图时,不断得到相同的错误,并且我对如何解决它相当迷失。如有任何帮助,我将不胜感激。

#Annuity-due function
AnU = function(x, n, i)
{
An = 0
for (k in 0:(n-1))
{
An = An + (1/(1+i))^k*lx[x+k]/lx[x]
}
return(An)
}
#Term/whole life assurance function
TWa <- function(x, n, i){
if (missing(n)) 
n = 120 - x - 1
Ta = 0
for(k in 0:(n-1))
{
Ta = Ta + (1/(1+i))^(k+1)*(lx[x+k]-lx[x+k+1])/lx[x]
}
return(Ta)
}
#Setting Premium
P <- 100000*TWa(x = 25, n = 40, i = 0.04)/AnU(x = 25, n = 40, i = 0.04)
#Policy value function
age <- c(1:120)
term <- c(1:120)
time <- c(1:120)
policy_TW <- function(time, age, term, rate)
return(100000*TWa(x = age + time, n = term - time, i = rate) -
P * AnU(x = age + time, n = term - time, i = rate))
for (time in 0:40)
cat("At time", time, " policy value is ", policy_TW(time, 25, 40, 0.04), "n")
#Plot
plot(0:40, policy_TW(0:40, 25, 40, 0.04), ylim = c(0,6000), type = "b")
> plot(0:40, policy_TW(0:40, 25, 40, 0.04), ylim = c(0,6000), type = "b")
Warning messages:
1: In 0:(n - 1) :
numerical expression has 41 elements: only the first used
2: In 0:(n - 1) :
numerical expression has 41 elements: only the first used

编辑:为了再现性,我忘了添加lx代码。这是从链接的xls文件计算出来的,该文件随后被命名为datahttps://www.actuaries.org.uk/documents/am92-permanent-assurances-males

# Calculate the values for lx
qx = c(rep(NA,16),data$qx)
lx = vector()
lx[1:17] = c(rep(NA,16),10000)
for (i in 18:120)
{
lx[i]=lx[i-1]*(1-qx[i-1])
}

语法0:(n-1)创建一个序列,一个从0到n-1的单个整数向量。然而,您的n本身就是一个向量,因为它被定义为term - timetime是所有整数0到40的向量(因此它包含41个元素)。因此,只使用n的第一个元素来创建序列。例如,如果nc(4,5,10),则只使用4,忽略5和10,而0:(n-1)将返回c(0,1,2,3)

您需要重新定义AnU()TWa()函数。我不确定你到底需要什么,但我认为你可以用for (k in 0:(max(n)-1))代替for (k in 0:(n-1))。我想测试这一点,但我无法重现你的错误,因为对象lx,这是在两个函数的公式中,没有在你的代码中定义。

相关内容

最新更新