title: How to "sort(unique(x))" or faster method on many variables with data.table?
body: <p>I want to change 12 variables with 10+mill rows, so I'm looking for something fast.</p>
  
  <p>Sample dataset</p>
  
  <pre><code>library(data.table)
  set.seed(1)
  (DT &lt;- data.table(
    V1 = sample(LETTERS[1:3], size=10, replace=TRUE),
    V2 = sample(letters[5:9], size=10, replace=TRUE)))
  
  str(DT)
  Classes ‘data.table’ and 'data.frame':  10 obs. of  2 variables:
   $ V1: chr  "A" "C" "A" "B" ...
   $ V2: chr  "g" "e" "i" "i" ...
   - attr(*, ".internal.selfref")=&lt;externalptr&gt; 
  </code></pre>
  
  <p>I want to change <code>V1</code> and <code>V2</code> (12 variables in real dataset with 10+ mill rows) to ordered factors. This works, but I know I shouldn't...</p>
  
  <pre><code>DT[, V1 := factor(V1, levels = sort(unique(V1)), ordered = TRUE)]
  DT[, V2 := factor(V2, levels = sort(unique(V2)), ordered = TRUE)]
  
  str(DT)
  Classes ‘data.table’ and 'data.frame':  10 obs. of  2 variables:
   $ V1: Ord.factor w/ 3 levels "A"&lt;"B"&lt;"C": 1 3 1 2 1 3 3 2 2 3
   $ V2: Ord.factor w/ 4 levels "e"&lt;"f"&lt;"g"&lt;"i": 3 1 4 4 2 2 1 4 4 1
   - attr(*, ".internal.selfref")=&lt;externalptr&gt; 
  </code></pre>
  
  <p>From <a href="https://stackoverflow.com/questions/36953026/what-is-the-fastest-way-to-get-a-vector-of-sorted-unique-values-from-a-data-tabl">this post</a> I know that <code>DT[, .N, by = V1][order(-N), V1]</code> is faster than <code>sort(unique(x))</code>. So I said "piece of cake"...</p>
  
  <pre><code>cols &lt;- c("V1", "V2")
  for (i in cols) {
    # faster than sort(unique(x))
    levs &lt;- DT[, .N, by = mget(i)][order(-N), mget(i)][[1]]
  
    # all variables in cols, to ordered factor
    DT[, mget(i) := factor(mget(i), levels = levs, ordered = TRUE)]
    }
  </code></pre>
  
  <p>... and it doesn't work. I've also tried building the unique sorted levels with lapply <code>levs &lt;- lapply(DT[,..cols), function(x) { sort(unique(x)) })</code> but I cant assign the levels to each variable</p>
  
  <p>=(</p>