I’m curious as to whether someone in the Stan community (or the Stan developers themselves) has worked on a function to compute the number of unique elements in a vector (or other such data structure) that is equivalent to R’s version of unique().

rstan::lookup(unique)

reveals “no matching Stan functions”

If not, I think it should be fairly straightforward to include some code in the functions block to accomplish this task.

No. You could write a Stan function that calls sort_desc and then check how many times the i-th element is equal to the previous element. Then you could allocate a local vector with that size and resweep through the sorted vector to pull out those elements and put them into the local vector that you could then return.

functions {
int[] unique(int[] x) {
// error occurs here with declaring res as int[]
int[] res = sort_desc(x);
for (i in 1:num_elements(res)) {
res[i] = ...; // to be filled in later
}
}
}

but keep getting a

PARSER EXPECTED: <identifier>

error.

I highly doubt this is a bug in STAN itself.

sort_desc is an integer vector int[], so the error is occurring on the left-hand side of that statement.

Given the generic error, I’ve read it could be due to something silly like using a reserved keyword as a variable name. However, this is not the case here.

While I’m essentially a newbie to STAN, what I’ve seen in the STAN manuals, forums and YouTube videos so far is pretty cool. I will definitely be converting all my computationally-expensive JAGS models to STAN!