Acessing element out of range - Multinomial Regression

Hello,
First time poster. I am trying to fit a multinomial regression model in RStan. I have species richness counts/outcome value (1-8) and vegetation types (1-14) from 645 sites. I am trying to estimate the probability of species richness count for each vegetation type. However when I try to run Stan I get this error returned:

SAMPLING FOR MODEL ‘6b9f964743cbd2e39ffe150107d8dddf’ NOW (CHAIN 1).
Chain 1: Unrecoverable error evaluating the log probability at the initial value.
Chain 1: Exception: []: accessing element out of range. index 8 out of range; expecting index to be between 1 and 7; index position = 1b_veg (in ‘model84e0b6f6c72_6b9f964743cbd2e39ffe150107d8dddf’ at line 15)

[1] “Error in sampler$call_sampler(args_list[[i]]) : "
[2] " Exception: []: accessing element out of range. index 8 out of range; expecting index to be between 1 and 7; index position = 1b_veg (in ‘model84e0b6f6c72_6b9f964743cbd2e39ffe150107d8dddf’ at line 15)”
[3] “In addition: Warning message:”
[4] “In system(paste(CXX, ARGS), ignore.stdout = TRUE, ignore.stderr = TRUE) :”
[5] " ‘-E’ not found"

I’m really at a loss for determining what is wrong. My index should be 8, because there are 8 species richness counts. Am I missing something?
Here is what my data looks like:

List of 4
 $ N   : num 645
 $ K   : num 8
 $ rich: num [1:645] 3 3 6 1 3 5 7 6 7 4 ...
 $ veg : num [1:645] 5 8 14 10 12 7 8 11 14 9 ...

data{
  int N; // number of observations
  int K; // number of outcome values
  int rich[N]; // species richness
  int veg[N]; // veg code
}
parameters{
  vector[K-1] b_veg; // intercepts
}
model{
  b_veg ~ normal(0,1); // prior
  for ( i in 1:N ) {
  vector[K] p;
    for ( j in 1:(K-1) ) p[j] = b_veg[veg[i]];
    p[K] = 0; // the pivot
    rich[i] ~ categorical_logit( p );
  }
}

Thanks for your help in advance.
Alan

Welcome!

I think this might be the problem. In the data it looks like veg[i] can be bigger than 7 but you’re using it to index a parameter vector that only has 7 elements.

Thanks Jonah,

This worked “b_veg[j]*veg[i]”
Indexing will always be my Achilles heel.

1 Like