title: Calculate multiple aggregations on several variables using lapply(.SD, ...)
body: <p>I'd like to perform multiple aggregations, using <code>data.table</code>'s <code>lapply(.SD, ...)</code> approach, i.e. calculate several different summary statistics on several variables. But my guesses as to how to do this end in either errors or the equivalent of <code>rbind</code> rather than <code>cbind</code>.</p>
  <p>For example, to get the mean and median mpg in mtcars by cyl, one could do the following:</p>
  <pre><code>mtcars.dt &lt;- data.table(mtcars)
  mtcars.dt[, list(mpg.mean = mean(mpg), mpg.median = median(mpg)), by = &quot;cyl&quot;]
  # Result:
      cyl mpg.mean mpg.median
  |1:   6    19.74       19.7
  |2:   4    26.66       26.0
  |3:   8    15.10       15.2
  </code></pre>
  <p>But applying the <code>.SD</code> approach either <code>rbind</code>s the result on the functions:</p>
  <pre><code>mtcars.dt[, lapply(.SD, function(x) list(mean(x), median(x))),
            by = &quot;cyl&quot;, .SDcols = c(&quot;mpg&quot;)]
  # Result:
     cyl              mpg
  1:   6 19.7428571428571
  2:   6             19.7
  3:   4 26.6636363636364
  4:   4               26
  5:   8             15.1
  6:   8             15.2
  </code></pre>
  <p>Or breaks altogether:</p>
  <pre><code>mtcars.dt[, lapply(.SD, list(mean, median)),
            by = &quot;cyl&quot;, .SDcols = c(&quot;mpg&quot;)]
  # Result:
  # Error in `[.data.table`(mtcars.dt, , lapply(.SD, list(mean, median)),  :
  #  attempt to apply non-function
  </code></pre>
  <p>EDIT: As Senor O noted, some answers provided work for my example, but only because there's a single aggregation column. An ideal solution would work for multiple columns, for example replacing the following:</p>
  <pre><code>mtcars.dt[, list(mpg.mean = mean(mpg), mpg.median = median(mpg), 
                   hp.mean = mean(hp), hp.median = median(hp)), by = &quot;cyl&quot;]
  # Result:
     cyl mpg.mean mpg.median hp.mean hp.median
  1:   6    19.74       19.7  122.29     110.0
  2:   4    26.66       26.0   82.64      91.0
  3:   8    15.10       15.2  209.21     192.5
  </code></pre>
  <p>However, even if it works for a single column, it can still be useful. For example, my immediate use case is a function which takes a column name as a string and calculates multiple grouped-by metrics for it, something which is not possible without <code>.SDcols</code> AFAIK.</p>