I am making a user-defined function and am trying to take a random sample from values 1:100 and then use that random sample to index a matrix.This is how I would write it in R.

Ind = sample(1:100, 100)
B[ ,1] = A[ , Ind]

But I am running into issues with taking a vector of real numbers and making them into an integer. Is there a function that I am missing like ‘as.integer’ ? Additionally there is not a function in Stan to replace ‘sample()’ so I have gone with uniform_rng. This is what I have translated so far. Any suggestions?

vector[100] x;
int Ind[100];
x = uniform_rng(1, Q);
Ind = x;
B[ ,1] = A[ ,Ind] ;

thank you @nhuurre. That solved my integer and sampling problem! I am finding myself with another vector that is derived from summing a column in a matrix that I also want to make into an integer for indexing another matrix. i.e.

matrix[100, 100] z;
for ( i in 1:100) {
y[i] = sum(x[ ,i]);
}
z[ ,1] = y;

Y is made up of integers but outputted as reals. Are there any functions for converting reals into integers?

Just double-checking: you know that these functions can only be used in the TD and GQ sections, right? Stan doesn’t permit any kind of randomness in the TP & model blocks.

No, there aren’t. If x (and y) is integer data then you should declare it as array[N,M] int instead of matrix[N,M]. If x is a parameter matrix then you can’t do this inside the Stan model.

Remember, as in the other post, to work backwards from the type you need to ultimately use downstream. As @nhuurre says, if you need integers then work backwards from that and don’t store anything upstream in a matrix, but rather in an integer array.

However, in the weird case where you actually need to multiply/invert/decompose matrices in order to generate integers to be used for indexing exclusively ingenerated quantities or transformed data (where real-to-integer conversion won’t break the HMC sampler), then you could use the hacks discussed in the link below to accomplish what you need. However, once you reach that point I strongly suspect that it would be simpler to precompute the transformed data (e.g. in R or python) and pass them as data, or to post-compute the generated quantities (e.g. in R or python) from the fitted model object.

Thanks @nhuurre and @jsocolar and for all your input. I would have truly benefited from starting at the end of my function when I started started translating R.