# Inverse quantile function for datasets

Hi, I need a function to retrieve the observation which corresponds to a certain quantile of a variable. I am using this function to calculate the quantile value, given a vector of observation (note that I did not write the function, I found it here)

``````functions {
real quantile(vector x, real p){
int n;            // length of vector x
real index;       // integer index of p
int lo;           // lower integer cap of the index
int hi;           // higher integer cap of the index
real h;           // generated weight between the lo and hi
real qs;          // weighted average of x[lo] and x[hi]
n = num_elements(x);
index = 1 + (n - 1)*p;
lo = 1;
while ((lo + 1) < index)
lo = lo + 1;
hi = lo + 1;
h = index - lo;
qs = (1 - h)*sort_asc(x)[lo] + h*sort_asc(x)[hi];
return qs;
}
}
``````

I am not too good with programming, I was wondering if it were possible, with a few modification, to make the function retrieve the “id” of the observation which represents a specific quantile.

For example, let us assume I have a dataset of height, weight and numbered id’s, from 1 to 100 let’s say. I would like to feed the function the vector of heights and retrieve the weight associated to the individual with the median height. Would that be simple to code? And if yes how could I do it? Thanks in advance for all the help.

You can return that value and then look it up using @jonah’s code in Stan equivalent to R's which() - #13 by jonah to return the positions of those values.

2 Likes