Declaring integer of length 1 fails? as in: `int X[1]`

I’m declaring an integer with user-defined length:

 data {
  int n;
  int index[n];
}

If n equal 1 this will cause the model to fail with the following message:

Error in new_CppObject_xp(fields$.module, fields$.pointer, ...) : 
  Exception: mismatch in number dimensions declared and found in context; processing stage=data initialization; variable name=index; dims declared=(1); dims found=()  (in 'model1ba41afa49ce_127aa55ea50e293e0a07a9b5107d2ac7' at line 4)

failed to create the sampler; sampling not done

Here’s an example:

library(rstan)

model  <-  "
    data {
      int n;
      int index[n];
    }
    generated quantities {
      int return_index[n];
      for (i in 1:n) {
        return_index[i] = index[i];
      }
    }"

works <- stan(model_code = model, 
         data = list(n = 2, index = 1:2), 
         algorithm = "Fixed_param")

fails <- stan(model_code = model, 
             data = list(n = 1, index = 1), 
             algorithm = "Fixed_param")

Of course the point of the brackets is usually to index multiple integers. Typically its not a problem because you can just declare int index but with pre-compiled models for an R package this is limiting; I’m trying to create a missing data model and this means that the model won’t work if you have one missing observation. Am I missing something?

I tried setting data to list(n = 1, index = as.array(1)), and that got the sampler to run. I think the problem was not the int index[1] declaration, but that RStan treated index = 1 as setting index to an integer rather than to an array that happened to only have a single element with the value of 1.

2 Likes

Thanks! That does it.