title: Using conditional statements in r data.table
body: <p>I am trying to use data.table to recode a variable based on certain conditions. My original dataset has around 30M records and after all variable creation around 130 variables. I used the methods suggested here: <a href="https://stackoverflow.com/questions/17018564/conditional-statements-in-data-table">conditional statements in data.table</a> <strong>(M1)</strong> and also here <a href="https://stackoverflow.com/questions/17450696/data-table-proper-way-to-do-create-a-conditional-variable-when-column-names-are">data.table: Proper way to do create a conditional variable when column names are not known?</a> <strong>(M2)</strong></p>
  
  <p>My goal is get the equivalent of the below code but something that is applicable using data.table</p>
  
  <pre><code>samp$lf5 &lt;- samp$loadfactor5
  
  samp$lf5 &lt;- with(samp, ifelse(loadfactor5 &lt; 0, 0, lf5))
  </code></pre>
  
  <p>I will admit that I don't understand .SD and .SDCols very well, so I might be using it wrong. The code and errors from <strong>(M1)</strong> and <strong>(M2)</strong> are given below and the <strong>sample dataset is here: <a href="http://goo.gl/Jp97Wn" rel="noreferrer">http://goo.gl/Jp97Wn</a></strong></p>
  
  <p><strong>(M1)</strong></p>
  
  <pre><code>samp[,lf5 = if(loadfactor5 &lt;0) 0 else loadfactor5]
  </code></pre>
  
  <p>Error Message</p>
  
  <pre><code>Error in `[.data.table`(samp, , lf5 = if (loadfactor5 &lt; 0) 0 else loadfactor5) : 
  unused argument (lf5 = if (loadfactor5 &lt; 0) 0 else loadfactor5)
  </code></pre>
  
  <p>When I do this:</p>
  
  <pre><code>samp[,list(lf5 = if(loadfactor5 &lt;0) 0 else loadfactor5)]
  </code></pre>
  
  <p>it gives lf5 as a list but not as part of the samp data.table and does not really apply the condition as lf5 still has values less than 0.</p>
  
  <p><strong>(M2)</strong></p>
  
  <pre><code>Col1 &lt;- "loadfactor5"
  Col2 &lt;- "lf5"
  
  setkeyv(samp,Col1)
  samp[,(Col2) :=.SD,.SDCols = Col1][Col1&lt;0,(Col2) := .SD, .SDcols = 0]
  </code></pre>
  
  <p>I get the following error</p>
  
  <pre><code>Error in `[.data.table`(samp, , `:=`((Col2), .SD), .SDCols = Col1) : 
  unused argument (.SDCols = Col1)
  </code></pre>
  
  <p>Any insights on how to finish this appreciated. My dataset has 30M records so I am hoping to use data.table to really cut the run time down.</p>
  
  <p>Thanks,</p>
  
  <p>Krishnan</p>