title: Conditional sum of Data Table by key in R
body: <p>I have a data table 'df' with 3 columns. id , meal , time
  Each id has many rows.</p>
  
  <pre><code>library(data.table)
  id = c(1,1,2,2,3,3)
  meal = c(1,1,0,0,1,0)
  time = c(10,9,12,13,7,15)
  df &lt;- data.table(id, meal, time)
  
  &gt; df
     id meal time
  1:  1    1   10
  2:  1    1    9
  3:  2    0   12
  4:  2    0   13
  5:  3    1    7
  6:  3    0   15
  </code></pre>
  
  <p>Now, I want to calculate the sum of time when meal == 1 of each ID.
  My current code is:</p>
  
  <p><code>df[meal == 1, sum(time), by = "id"]</code></p>
  
  <p>However, this code excute meal == 1 first, 
  so when some id have no record with meal == 1, it would be omit instead of return 0. </p>
  
  <p>id 2 is omitted here.</p>
  
  <pre><code>   id V1
  1:  1 19
  2:  3  7
  </code></pre>
  
  <p>What can I do?</p>