title: data.table assign new columns based on variable
body: <p>A follow-up on this <a href="https://stackoverflow.com/questions/59088378/pivot-wider-based-on-condition-of-a-0-or-1">question</a>, can a <code>data.table</code> refer to a variable inside of the DT to create new columns?</p>
  
  <p>The other question wanted to turn this table:</p>
  
  <pre><code>library(data.table)
  dt &lt;- data.table(
    dates = c("2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05"),
    yes_no = c(0, 1, 0, 1, 1) 
  )
          dates yes_no
  1: 2017-01-01      0
  2: 2017-01-02      1
  3: 2017-01-03      0
  4: 2017-01-04      1
  5: 2017-01-05      1
  </code></pre>
  
  <p>Into this:</p>
  
  <pre><code>        dates yes_no 2017-01-02 2017-01-04 2017-01-05
  1: 2017-01-01      0          0          0          0
  2: 2017-01-02      1          1          0          0
  3: 2017-01-03      0          0          0          0
  4: 2017-01-04      1          0          1          0
  5: 2017-01-05      1          0          0          1
  </code></pre>
  
  <p>I wanted to update-by-reference but do not know how to make new columns based on what is in the <code>data.table</code>. That is, the LHS of the <code>:=</code> operator does not appear to look in the <code>data.table</code> environment which makes this fail:</p>
  
  <pre><code>## tried
  dt[yes_no == 1, as.character(dates) := as.data.frame(diag(.N))]
  </code></pre>
  
  <blockquote>
    <p>Error in eval(lhs, parent.frame(), parent.frame()) : 
      object 'dates' not found</p>
  </blockquote>
  
  <pre><code>## used:
  ind &lt;- dt[['yes_no']] != 0
  cols &lt;- as.character(dt[['dates']])[ind]
  
  dt[, (cols) := 0L]
  dt[ind, (cols) := as.data.frame(diag(.N))]
  ## also valid
  # set(d, which(ind), cols, as.data.frame(diag(length(cols))))
  </code></pre>
  
  <p>Is there a more direct way to make this work?</p>
  
  <pre><code>dt[yes_no == 1, as.character(dates) := as.data.frame(diag(.N))]
  </code></pre>