Not working function in Stan manual(s): permutation_rng

The cross validation entry has a function permutation_rng:

functions {
  array[] int permutation_rng(int N) {
     int N = rows(x);
     array[N] int y;
     for (n in 1:N) {
       y[n] = n;
     }
     vector[N] theta = rep_vector(1.0 / N, N);
     for (n in 1:rows(y)) {
       int i = categorical_rng(theta);
     }
      array[n] int temp = y;
      y[n] = y[i];
      y[i] = temp;
     }
     return y;
  }
}

This function doesn’t make sense to me: the loop index n is found outside the for loop; x is not defined; the penultimate line tries to assign the entire array temp into y[i] which is incompatible; and finally there seems to be an uneven number of curly brackets. I’m trying to run cross-validation and both this function and also the function in the old version of the manual (which is still up online) are both odd. I seem to be too much of a noob to quickly figure out the synax error(s) that stop this function from working, but once I find out how to make this do what it’s supposed to I’ll post my version of the function up on this post. Probably lots of people here can beat me to it though so posting it up on the forums.

Any guidance appreciated

I believe a correct version of the function is:

functions {
  array[] int permutation_rng(int N) {
    array[N] int y;
    for (n in 1 : N) {
      y[n] = n;
    }
    vector[N] theta = rep_vector(1.0 / N, N);
    for (n in 1 : size(y)) {
      int i = categorical_rng(theta);
      int temp = y[n];
      y[n] = y[i];
      y[i] = temp;
    }
    return y;
  }
}

Thanks for catching this problem in our docs! I’ll make sure the original page also gets fixed up

1 Like