title: R Data.Table create a variable with a condition
body: <p>I need to create a new variable in the dataset below: </p>
  
  <pre><code>A  X
  a  1
  b  2
  c  3
  d  4
  e  5
  f  6
  g  7
  h  8
  i  9
  j 10
  </code></pre>
  
  <p>The <code>newvar</code> will have value 1 if <code>X</code> equals 2,5,7 or 9. Otherwise, <code>newvar</code> should be 0.  </p>
  
  <p>Code:</p>
  
  <pre><code>dt1 &lt;- data.table(A = letters[1:10], X = 1:10, key = "X")
  numberlist &lt;- list(2,5,7,9)
  </code></pre>
  
  <p>I have tried the following based on a post <a href="https://stackoverflow.com/questions/17450696/data-table-proper-way-to-do-create-a-conditional-variable-when-column-names-are">here</a>:</p>
  
  <pre><code>dt1[, newvar:=.SD, .SDcols = 0][%in% numberlist, newvar:=.SD, .SDcols = 1]
  dt1[, newvar:=.SD, .SDcols = 0][X %in% numberlist, newvar:=.SD, .SDcols = 1]
  </code></pre>
  
  <p><code>dt1[, newvar:=.SD, .SDcols = 0]</code> means "assign value of 0 to newvar as default option. The second bracket <code>[%in% numberlist, newvar:=.SD, .SDcols = 1]</code> means "if the key (X) is included in the numberlist, set the <code>newvar</code> value to 1.</p>
  
  <p>Any idea why it is not working? </p>