2

I need to pass the data as a list of vectors with various length and a list of matrices with the same number of rows but with a different number of columns. Is there a way to pass the data in Rstan?

  • 1
    There's a chapter in the Stan user's guide that explains how to pack and unpack ragged arrays. There's no native support yet, so you either have to pad as Ben suggests in his answer or encode the way described in the user's guide. – Bob Carpenter Mar 27 '19 at 14:17

1 Answers1

5

The answer is essentially no, the Stan language does not allow ragged data structures such as vectors with different lengths, matrices with different numbers of columns, etc.

Depending on your application, it may be easiest to use padding or flattening. By padding I mean adding extra values to your vectors or extra columns to your matrices so that they are all the same size. It is best to use Inf or -Inf as the padded values so that it is easier to spot mistakes if they accidentally get utilized in the target log-kernel. By flattening, I mean making a single long vector by concatenating your vectors of various lengths and the same goes for vectors. Then reform them as vectors and matrices of appropriate sizes in local blocks of your Stan program. In both cases, you would also need to pass the sizes of everything as integer arrays.

Another possibility is to use some script to declare each vector or matrix that you need in the data block, even though they are different sizes. That is simple enough to do but it can be hard to generating the corresponding code to utilize each of them.

Ben Goodrich
  • 4,870
  • 1
  • 19
  • 18
  • Thank you. The good thing is that my list of matrices has the same number of rows so it makes the flattening easier to do. – Scarlet Rice Mar 27 '19 at 21:50