Sam Webb
Sam Webb

Reputation: 23

Not sure how to fix the 'numerical expression has 41 elements: only the first used' warning

Currently trying to write functions to compute assurance benefits and reserves/ policy values although when trying to plot, keep getting the same error and am pretty lost at to how I solve it. Any help will be greatly appreciated.

#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

Edit: For purpose of reproducibility, I forgot to add the lx code. This has been calculated from the linked xls file which is then named data https://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])
}

Upvotes: 2

Views: 478

Answers (1)

qdread
qdread

Reputation: 3973

The syntax 0:(n-1) creates a sequence, a single vector of integers going from zero to n-1. However your n is itself a vector, because it is defined as term - time and time is a vector of all integers 0 to 40 (hence it contains 41 elements). So only the first element of n is used to create the sequence. For example if n was c(4,5,10), only the 4 would be used, ignoring 5 and 10, and 0:(n-1) would return c(0,1,2,3).

You would need to redefine the AnU() and TWa() functions. I am not sure exactly what you need but I think you can just replace the line for (k in 0:(n-1)) with for (k in 0:(max(n)-1)). I wanted to test this but I was unable to reproduce your error because the object lx, which is in the formula in both functions, is not defined in your code.

Upvotes: 1

Related Questions