title: R data.table: How to sum variables by group based on a condition?
body: <p>Let's say I have the following R <code>data.table</code> (though I'm happy to work with base R, data.frame as well)</p>
  
  <pre><code>library(data.table)
  
  dt = data.table(Category=c("First","First","First","Second","Third", "Third", "Second"), Frequency=c(10,15,5,2,14,20,3), times = c(0, 0, 0, 3, 3, 1))
  
  &gt; dt
     Category Frequency times
  1:    First        10     0
  2:    First        15     0
  3:    First         5     0
  4:   Second         2     3
  5:    Third        14     3
  6:    Third        20     1
  7:   Second         3     0
  </code></pre>
  
  <p>If I wished to sum the Frequencies by Category, I would use the following:</p>
  
  <pre><code>data[, sum(Frequency), by = Category]
  </code></pre>
  
  <p>However, let's say I wanted to sum <code>Frequency</code> by <code>Category</code> if and only if <code>times</code> is non-zero and not equal to <code>NA</code>?</p>
  
  <p>How would one make this sum a conditional based on the values of a separate column?</p>
  
  <p>EDIT: apologies for the obvious question. A quick addition: what about if the elements of a certain column are strings?</p>
  
  <p>e.g. </p>
  
  <pre><code>&gt; dt
     Category Frequency times
  1:    First        ten    0
  2:    First        ten    0
  3:    First        five   0
  4:   Second        five   3
  5:    Third        five   3
  6:    Third        five   1
  7:   Second        ten    0
  </code></pre>
  
  <p><code>Sum()</code> will not calculate the frequencies of <code>ten</code> versus <code>five</code></p>