title: Using multiple functions depending on variable with data.table
body: <p>I want to make my code more concise but the current implementation I have is much less efficient than the more verbose method.</p>
  
  <p>Why is the verbose method so much faster than the concise method and is there a way to make it more concise without sacrificing speed?</p>
  
  <pre class="lang-r prettyprint-override"><code>library(data.table)
  mtcars_dt &lt;- as.data.table(mtcars)
  
  min_vars &lt;- c("mpg", "cyl")
  max_vars &lt;- c("hp", "gear")
  
  # Preferred but slow  method
  system.time(mtcars_dt[, c(lapply(.SD[, .SD, .SDcols = ..min_vars], min, na.rm = TRUE),
                            lapply(.SD[, .SD, .SDcols = ..max_vars], max, na.rm = TRUE)),
                        by = wt])
  #&gt;    user  system elapsed 
  #&gt;    0.05    0.02    0.04
  
  # Not concise but fast method
  system.time(mtcars_dt[, .(mpg = min(mpg, na.rm = TRUE),
                            cyl = min(cyl, na.rm = TRUE),
                            hp = max(hp, na.rm = TRUE),
                            gear = max(gear, na.rm = TRUE)),
                        by = wt])
  #&gt;    user  system elapsed 
  #&gt;       0       0       0
  
  # Check if results from two methods are equal
  x &lt;- mtcars_dt[, c(lapply(.SD[, .SD, .SDcols = ..min_vars], min, na.rm = TRUE),
                lapply(.SD[, .SD, .SDcols = ..max_vars], max, na.rm = TRUE)),
            by = wt]
  
  y &lt;- mtcars_dt[, .(mpg = min(mpg, na.rm = TRUE),
                cyl = min(cyl, na.rm = TRUE),
                hp = max(hp, na.rm = TRUE),
                gear = max(gear, na.rm = TRUE)),
            by = wt]
  
  all.equal(x, y)
  #&gt; [1] TRUE
  </code></pre>
  
  <p><sup>Created on 2019-12-24 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>