title: R: include factors with no entries when using dcast
body: <p>I am using the reshape2 function dcast on a dataframe. One of the variables is a factor where some of the levels do not appear in the dataframe, but I would to include all values in the new columns created.</p>
  
  <p>For example say I run the following</p>
  
  <pre><code>library(reshape2)
  dataDF &lt;- data.frame(
    id = 1:6,
    id2 = c(1,2,3,1,2,3),
    x = c(rep('t1', 3), rep('t2', 3)),
    y = factor(c('A', 'B', 'A', 'B', 'B', 'C'), levels = c('A', 'B', 'C', 'D')),
    value = rep(1)
  )
  
  dcast(dataDF, id + id2 ~ x + y, fill = 0)
  </code></pre>
  
  <p>I get the following</p>
  
  <pre><code>  id id2 t1_A t1_B t2_B t2_C
  1  1   1    1    0    0    0
  2  2   2    0    1    0    0
  3  3   3    1    0    0    0
  4  4   1    0    0    1    0
  5  5   2    0    0    1    0
  6  6   3    0    0    0    1
  </code></pre>
  
  <p>But I also want to include the columns t1_C, t1_D, t2_A and t2_D full of 0's</p>
  
  <p>i.e. I want the following</p>
  
  <pre><code>  id id2 t1_A t1_B t1_C t1_D t2_A t2_B t2_C t2_D
  1  1   1    1    0    0    0    0    0    0    0
  2  2   2    0    1    0    0    0    0    0    0
  3  3   3    1    0    0    0    0    0    0    0
  4  4   1    0    0    0    0    0    1    0    0
  5  5   2    0    0    0    0    0    1    0    0
  6  6   3    0    0    0    0    0    0    1    0
  </code></pre>
  
  <p>Also, as an aisde, would it be possible to create the above without having the column 'value' full of ones in the initial dataframe. Basically just want to cast x &amp; y in their own columns with a 1 if they exist in that id.</p>
  
  <p>Thanks in advance</p>
  
  <p>EDIT:
  Initially had one variable on LHS which Jeremy answer below, but actual have more than one variable on LHS so edited question to reflect this</p>