Stan equivalent of R::unique()

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.

Thanks I have started to code this up as follows:

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.

Do you see my error?

i am running in Stan Version 2.21.2

The declaration needs a size.

int[num_elements(x)] res = sort_desc(x);
1 Like

Hmm… when I try this solution, I still receive the same error.

For an integer array it should actually be

int res[num_elements(x)]  = sort_desc(x);

with the size declaration after the name res. But this

Identifier expected after sized type in local (or model block) variable declaration. (No transformations/constraints allowed.)

is a confusing error message! We should improve that if possible.

2 Likes

Thanks.

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!

I will also accept your answer as a solution,

2 Likes

Glad that works now.

Glad to hear that. Welcome to the Stan community!

(By the way, Stan is actually not an acronym, so it’s Stan and not STAN. We see that all the time though!)

Something for @rybern?