# Implementing an empircal r-th q-quantile

**URL:** <https://discourse.julialang.org/t/implementing-an-empircal-r-th-q-quantile/83453>\
**Category:** Statistics\
**Tags:** question, statistics, distributions\
**Created:** [June 28, 2022, 11:16am UTC](https://discourse.julialang.org/t/implementing-an-empircal-r-th-q-quantile/83453 "2022-06-28T11:16:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rikh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rikh/32/204104_2.png) [@rikh](https://discourse.julialang.org/u/rikh)\
**Post date:** [June 28, 2022, 11:16am UTC](https://discourse.julialang.org/t/implementing-an-empircal-r-th-q-quantile/83453/1 "2022-06-28T11:16:19Z")

</div>

I’m trying to implement an algorithm from a paper which makes use of empirical r-th q-quantiles of the marginals X^{(1)}, ..., X^{(p)} for a dataset X with p features (Bénard et al., [2021](http://proceedings.mlr.press/v130/benard21a.html)).

If I understand this correctly, this means that for each feature in the dataset, q-quantiles should be determined.

Would the following be the correct way to determine an “empirical 3-quantile” for some column in the dataset X^{(u)}?

```julia
julia> using StatsBase

julia> q = 3;

julia> X⁽ᵘ⁾ = [1, 2, 3];

julia> StatsBase.nquantile(X⁽ᵘ⁾, q)
4-element Vector{Float64}:
 1.0
 1.6666666666666667
 2.3333333333333335
 3.0

```

---

<div class="post-metadata">

**Author:** ![rikh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rikh/32/204104_2.png) [@rikh](https://discourse.julialang.org/u/rikh)\
**Post date:** [June 28, 2022, 12:28pm UTC](https://discourse.julialang.org/t/implementing-an-empircal-r-th-q-quantile/83453/2 "2022-06-28T12:28:55Z")

</div>

They give a definition too for the r-th q-quantile a \hat{q}\_{n,r}^{(j)} of \{ X\_i^{(j)}, ..., X\_n^{(j)} \} for r \in \{1, ..., q - 1\}. It is defined in Equation 4.2 in Bénard et al. ([2021](https://doi.org/10.1214/20-EJS1792)) by

\hat{q}\_{n,r}^{(j)} = \inf \{ x \in \mathbb{R} \: : \: \frac{1}{n} \sum\_{i=1}^n \mathbb{1}\_{x\_i^{(j)} \le x} \ge \frac{r}{q} \}

**EDIT:**

Got it (probably) thanks to [Quantiles - Heinrich Hartmann](https://www.heinrichhartmann.com/archive/quantiles.html#empirical-quantiles):

```julia
function _empirical_quantile(V::AbstractVector, quantile::Real)
    @assert 0.0 ≤ quantile ≤ 1.0
    n = length(V)
    index = Int(floor(quantile * (n + 1)))
    if index == 0
        index = 1
    end
    if index == n + 1
        index = n
    end
    sorted = sort(V)
    return sorted[index]
end

function _cutpoints(V::AbstractVector, q::Int)
    quantiles = range(; start=0.0, stop=1.0, length=q)
    return _empirical_quantile.(Ref(V), quantiles)
end

```

```julia
julia> _cutpoints(1:10, 3)
3-element Vector{Int64}:
  1
  5
 10

```

Would still be great if someone could verify this. I don’t know much about mathematical statistics
