title: How to apply a function to a subset of data.table using by and exposing all columns to the function?
body: <p>When slicing a <code>data.table</code> by group(s), variables used to slice the data are not in the subset during the function execution. I demonstrate this using <code>debugonce</code>.</p>
  
  <pre><code>library(data.table)
  x &lt;- data.table(a = rep(letters[1:4], each = 3), b = rep(c("a", "b"), each = 6), c = rnorm(12))
  
  myfun &lt;- function(y) paste(y$a, y$b, y$c, collapse = "")
  
  &gt; debugonce(myfun)
  &gt; x[, myfun(.SD), by = .(b, a)]
  debugging in: myfun(.SD)
  debug: paste(y$a, y$b, y$c, collapse = "")
  Browse[2]&gt; y
              c
  1: -1.2662416
  2:  0.9818497
  3: -0.5395385
  </code></pre>
  
  <p>What I'm after is the functionality of the split-sapply paradigm, where I would slice a data.frame according to factor(s) and apply the function to all columns, that is, also including the variables which have been used to slice it (demonstrated below).</p>
  
  <pre><code>&gt; debugonce(myfun)
  
  &gt; sapply(split(x, f = list(x$b, x$a)), FUN = myfun)
  debugging in: FUN(X[[i]], ...)
  debug: paste(y$a, y$b, y$c, collapse = "")
  Browse[2]&gt; y
  a b          c
  1: a a -1.2662416
  2: a a  0.9818497
  3: a a -0.5395385
  </code></pre>