title: Combinatorics: select permutations if the sum is equal to a given value
body: <p>I have a data.table with two columns. The objective is to keep only the combinations of rows, for each "total_sum", where <code>sum(a) == total_sum</code>. So we need to generate all the possible combinations using <code>combn</code> for example and test them agains total_sum.</p>
  
  <p>I want maximize the number of rows that I keep so when there is more than one solution I want to keep the one with the maximum number of elements.</p>
  
  <p>If two combinations with the same number of elements are possible, then I can keep one or the other.</p>
  
  <p>I actually managed to solve this problem (I think) but my code is really slow. I have to apply this to a large dataset, so there must be a better way to do it.</p>
  
  <pre><code>set.seed(42)
  dt1 = data.table(a = sample(1:5, 18, replace = TRUE), total_sum = sample(4:8, 3, replace = TRUE))
  setkey(dt1, total_sum)
  a total_sum
   1: 5         6
   2: 5         6
   3: 5         6
   4: 4         6
   5: 4         6
   6: 1         6
   7: 4         6
   8: 3         6
   9: 5         6
  10: 2         6
  11: 5         6
  12: 5         6
  13: 2         8
  14: 3         8
  15: 4         8
  16: 4         8
  17: 3         8
  18: 1         8
  myft &lt;- function(a, total_sum) {
          len = length(a)
          for (i in len:1) {
              valid = match(a, combn(a, i)[, match(TRUE, combn(a, i, sum) == total_sum)], nomatch = FALSE) &amp; TRUE
              if (any(valid)) {
                  return (valid)
              }
          }
          return (rep(FALSE, len))
      }
      dt1[, .SD[myft(a, total_sum),], by = .(total_sum)]
     total_sum a
  1:         6 1
  2:         6 3
  3:         6 2
  4:         8 2
  5:         8 3
  6:         8 3
  </code></pre>