title: How to programmatically create binary columns based on a categorical variable in data.table?
body: <p>I have a big (12 million rows) <code>data.table</code> which looks like this:</p>
  
  <pre class="lang-r prettyprint-override"><code>library(data.table)
  set.seed(123)
  dt &lt;- data.table(id=rep(1:3, each=5),y=sample(letters[1:5],15,replace = T))
  &gt; dt
      id y
   1:  1 b
   2:  1 d
   3:  1 c
   4:  1 e
   5:  1 e
   6:  2 a
   7:  2 c
   8:  2 e
   9:  2 c
  10:  2 c
  11:  3 e
  12:  3 c
  13:  3 d
  14:  3 c
  15:  3 a
  </code></pre>
  
  <p>I want to create a new <code>data.table</code> containing my variable <code>id</code> (which will be the unique key of this new <code>data.table</code>) and 5 other binary variables each one corresponding to each category of <code>y</code> which take value <code>1</code> if the id has that value for <code>y</code>, <code>0</code> otherwise.<br>
  The output <code>data.table</code> should look like this:</p>
  
  <pre class="lang-r prettyprint-override"><code>   id a b c d e
  1:  1 0 1 1 1 1
  2:  2 1 0 1 0 1
  3:  3 1 0 1 1 1
  </code></pre>
  
  <p>I tried doing this in a loop but it's quite slow and also I don't know how to pass the binary variable names programmatically, as they depend on the variable I'm trying to "split".</p>
  
  <p><strong>EDIT</strong>: as @mtoto pointed out, a similar question has already been asked and answered <a href="https://stackoverflow.com/questions/11659128/how-to-use-cast-or-another-function-to-create-a-binary-table-in-r">here</a>, but the solution is using the <code>reshape2</code> package.<br>
  I was wondering if there's another (faster) way to do so by maybe using the <code>:=</code> operator in data.table, as I have a massive dataset and I'm working quite a lot with this package.</p>
  
  <p><strong>EDIT2</strong>: benchmark of the functions in @Arun's post on my data (~12 million rows, ~3,5 million different ids and 490 different labels for the <code>y</code> variable (resulting in 490 dummy variables)):</p>
  
  <pre class="lang-r prettyprint-override"><code>system.time(ans1 &lt;- AnsFunction())   # 194s
  system.time(ans2 &lt;- dcastFunction()) # 55s
  system.time(ans3 &lt;- TableFunction()) # Takes forever and blocked my PC
  </code></pre>