# CategoricalArray levels! allowmissing

**URL:** <https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960>\
**Category:** Data\
**Tags:** categoricalarrays\
**Created:** [September 9, 2021, 10:25pm UTC](https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960 "2021-09-09T22:25:38Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [September 9, 2021, 10:25pm UTC](https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960/1 "2021-09-09T22:25:38Z")

</div>

I am ordering the categories according to their frequency. What is wrong?

```julia
using CategoricalArrays, FreqTables
x = ["a", "b", "c", "c", missing]
cx = CategoricalArray(x)
lvls = names(sort(freqtable(collect(skipmissing(cx))), rev=true))
levels!(cx, lvls, allowmissing=true)

ERROR: LoadError: MethodError: Cannot `convert` an object of type CategoricalVector{String, UInt32, String, CategoricalValue{String, UInt32}, Union{}} to an object of type String

```

---

<div class="post-metadata">

**Author:** ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)\
**Post date:** [September 10, 2021, 7:22am UTC](https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960/2 "2021-09-10T07:22:26Z")

</div>

This is tricky indeed. You need to do:

```julia
lvls = unwrap.(names(sort(freqtable(collect(skipmissing(cx))), rev=true))[1])

```

@nalimilan - maybe we can consider allowing levels to be `CategoricalValue` also in `levels!` call?

---

<div class="post-metadata">

**Author:** ![nalimilan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nalimilan/32/147_2.png) [@nalimilan](https://discourse.julialang.org/u/nalimilan)\
**Post date:** [September 10, 2021, 9:27pm UTC](https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960/3 "2021-09-10T21:27:23Z")

</div>

Yeah, that’s something that I wanted to do for a long time. Let’s fix it at last: [https://github.com/JuliaData/CategoricalArrays.jl/pull/365](https://github.com/JuliaData/CategoricalArrays.jl/pull/365)

Though note that in your example you’ll need `levels!(cx, lvls[1], allowmissing=true)`.

We should probably provide more convenience methods to order levels by frequency and so on, like forcats in R.

---

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [October 23, 2021, 6:23pm UTC](https://discourse.julialang.org/t/categoricalarray-levels-allowmissing/67960/4 "2021-10-23T18:23:59Z")

</div>

Now that this is merged, is the solution the same as before?
