title: Create virtual categorical column based on existing values
body: <p>Reference: 
  <a href="https://stackoverflow.com/questions/36159321/transpose-and-create-categorical-values-in-r/36159469?noredirect=1#comment59957876_36159469">Transpose and create categorical values in R</a></p>
  
  <p>Follow-up to this question. While both model.matrix and data.table work very well with values already in it, how can we use them to simulate a column?</p>
  
  <p>Meaning, from data in the same data frame, </p>
  
  <pre><code>    data &lt;- read.table(header=T, text='
            subject weight sex  test 
            1       2      M     control 
            2       3      F     cond1  
            3       2      F     cond2  
            4       4      M    control
            5       3      F    control
            6       2      F    control
             ')
  </code></pre>
  
  <p>If I were to simulate the case statement with OR condition from SQL in R, how do I go about it? In SQL I would do:</p>
  
  <pre><code>case when ( sex = 'F' OR sex = 'M')  AND CONTROL IS NOT NULL THEN 1 ELSE 0 AS F_M_CONTROL
  case when (sex = 'F' OR sex = 'M') AND COND1 IS NOT NULL THEN 1 ELSE 0 AS F_M_COND1
  </code></pre>
  
  <p>bringing the output to: </p>
  
  <pre><code>subject      weight control_F_M control_M condtrol_F cond1_F_M cond1_F cond1_M
             1       2        0        1          0      0      0        0
             2       3        0        0          1      0      0        0
             3       2        0        0          0      0      1        0
             4       4        0        1          0      0      0        0
             5       3        1        0          0      0      0        0
             6       2        1        0          0      0      0        0
  </code></pre>
  
  <p>Any idea how I can generate the "Control_F_M" and Cond1_F_M columns in R?</p>
  
  <p>Thanks in advance,
  Bee</p>
  
  <p>Edit: </p>
  
  <p>To generate the afore mentioned output, i'm using the data table &amp; dcast as suggested before.</p>
  
  <p>I can use If-Else if I knew all the values in the column: test. I apologize for not clarifying this earlier. The challenge ofcourse is that the column is dynamic and so I'm hoping to generate that many columns dynamically as an extension to the below or using a similar approach.</p>
  
  <pre><code>           dcast(data, subject+weight~test+sex, fun=length, drop=c(TRUE,FALSE))
  </code></pre>