Create unique symbol in Julia, similar to Mathematica's `Unique[]`

Viewed 73

I need to populate a column of a data frame with unique factors. I have been using sequential integers, but I don't want to consumer of my function to be confused and think that they can do arithmetic on these values. These values are categorical with no definition for order, distance, and scale. In R, I would have solved this problem with as.factor. I see that there is a CategoricalArrays.jl project, which I have never used, that might offer similar functionality.

Mathematica has a useful Unique function that can create a (as the name implies) unique symbol.

In[1]:= Unique[]

Out[1]= $10

Julia has a similar Symbol that generates a lightweight value that I think makes sense to treat as a factor, but I haven't found a built-in technique to automatically generate unique symbols. You cannot invoke Symbol() without a parameter. I suppose I could call Symbol(UUIDs.uuid1()), but these are very long.

julia> using UUIDs

julia> Symbol(UUIDs.uuid1())
Symbol("8a9452d0-2451-11ec-08b4-3bb7f56a346a")

Is there an idiomatic way to generate short and unique symbols in Julia?

1 Answers

The way to generate unique Symbol is to use the gensym function.

However, I assume you most likely want to use CategoricalArrays.jl as you have commented. This package allows you to create arrays of both ordered or unordered factors - just like in R. The difference from R is that the user will be able to clearly see that what is stored in an array is a factor even after extracting it from an array, e.g.:

julia> using CategoricalArrays

julia> x = categorical(1:3)
3-element CategoricalArray{Int64,1,UInt32}:
 1
 2
 3

julia> x[1]
CategoricalValue{Int64, UInt32} 1

and as you can see the notion of being categorical is not lost which I guess is exactly what you want.

Related