Monte Carlo simulation for a frequency-severity model

Hi! I was trying to solve this exercise:

and the code below is what I believed would be the best fit:

N <- 10000
m <- 1000
lambda <- 0.005
p <- 0.01

S_function  = function(m,lambda,p){
  number.claims = rpois(m,lambda)
  n = sum(number.claims)
  x = matrix(NA, nrow = m, ncol = n)
  
  for (i in 1:m){
    for (j in 1:n){
      x[i,j] = rgeom(1,p)
    }
    #compute s_k
    s = apply(x,1,sum)
  }
  #total claim
  S = sum(s) 
  return(S)
}

S=array(NA, dim = N)
for (i in 1:N){
  S[i] = S_function(m,lambda,p)
}

However, when I run it, I get the error "Error in [<-(*tmp*, i, j, value = rgeom(1, p)) : subscript out of bounds," which I suppose is caused by the change in the size of x at each iteration. How can I solve this? It's frustrating to understand that the exercise is simple, but I can't solve it.

The "subscript out of bounds" error in R occurs when you try to access a row or column in a matrix or an element in a vector that does not exist. In the provided script, the error is likely caused by the matrix x having more columns than the number of claims in number.claims.

To fix this issue, you can modify the script to create the matrix x with the correct number of columns for each row based on the number of claims. Here's the corrected script:

N <- 10000
m <- 1000
lambda <- 0.005
p <- 0.01

S_function  = function(m, lambda, p) {
  number.claims = rpois(m, lambda)
  n = sum(number.claims)
  
  s = numeric(m)
  for (i in 1:m) {
    x = rgeom(number.claims[i], p)
    s[i] = sum(x)
  }
  
  # total claim
  S = sum(s)
  return(S)
}

S = numeric(N)
for (i in 1:N) {
  S[i] = S_function(m, lambda, p)
}

Created on 2023-07-05 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.