# Best way to discretize continuous variable

**URL:** <https://discourse.julialang.org/t/best-way-to-discretize-continuous-variable/62113>\
**Category:** New to Julia\
**Created:** [May 31, 2021, 8:08am UTC](https://discourse.julialang.org/t/best-way-to-discretize-continuous-variable/62113 "2021-05-31T08:08:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![danielw2904](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/danielw2904/32/10890_2.png) [@danielw2904](https://discourse.julialang.org/u/danielw2904)\
**Post date:** [May 31, 2021, 8:08am UTC](https://discourse.julialang.org/t/best-way-to-discretize-continuous-variable/62113/1 "2021-05-31T08:08:43Z")

</div>

I have a continuous variable that I would like to discretize based on the sample quantiles (e.g. top 1%, \>1%-top10%, etc). My intuition was to use the following

```julia
using StatsBase
x = sort(100 .*rand(100)); # sort just to see equivalent values in the same place
xf = ecdf(quantile(x, [0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99]))
xc = categorical(round.(xf.(x), digits = 5))

```

I round the values to hopefully get rid of floating point inaccuracy but this seems a bit hacky. Is there a better way?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [May 31, 2021, 9:31am UTC](https://discourse.julialang.org/t/best-way-to-discretize-continuous-variable/62113/2 "2021-05-31T09:31:41Z")

</div>

> [@danielw2904](#):
>
> `# sort just to see equivalent values in the same place`

I am not sure what you mean here, they are floats so in practice they will not coincide.

In any case, I would use something like

```julia
using StatsBase, CategoricalArrays
x = sort(100 .* rand(100))
breaks = quantile(x, [0.0, 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99, 1.0])
xc = cut(x, breaks; extend = true)

```

---

<div class="post-metadata">

**Author:** ![danielw2904](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/danielw2904/32/10890_2.png) [@danielw2904](https://discourse.julialang.org/u/danielw2904)\
**Post date:** [May 31, 2021, 1:15pm UTC](https://discourse.julialang.org/t/best-way-to-discretize-continuous-variable/62113/3 "2021-05-31T13:15:04Z")

</div>

> [@Tamas\_Papp](#):
>
> I am not sure what you mean here, they are floats so in practice they will not coincide.

I meant in the discretized form the values will be equivalent even if they are not equal to begin with.

Thank you that works great!
