title: data.table grouped operations with variable names of columns without slow DT[, mean(get(colName)), by = grp]
body: <p>I want to create a function which uses variable names of columns and variable name of data.</p>
  <p>This function is what I want and it works :</p>
  <pre><code>n &lt;- 1e7
  d &lt;- data.table(x = 1:n, grp = sample(1:1e5, n, replace = T))
  dataName = &quot;d&quot;
  colName = &quot;x&quot;
  
  # Objective :
  FOO &lt;- function(dataName = &quot;d&quot;,
           colName = &quot;x&quot;){
    get(dataName)[, mean(get(colName)), by = grp]
  }
  </code></pre>
  <p>The problem is that evaluation of <code>get()</code> for each group is very time-consuming. On a real data example it is 14 times longer than the static-name equivalent. I would like to reach the same execution time as if the column names were static.</p>
  <p>What I tried :</p>
  <pre><code>(cl &lt;- substitute(mean(eval(parse(text = colName))), list(colName = as.name(colName))))
  
  microbenchmark::microbenchmark(
  
    # 1) works and quick but does not use variable names of columns (654ms)
    (t1 &lt;- d[, mean(x), by = grp]),
  
    # 2) works but slow (1006ms)
    (t2 &lt;- get(dataName)[, mean(get(colName)), by = grp]), # works but slow
  
    # 3) works but slow (4075ms)
    (t3 &lt;- eval(parse(text = dataName))[, mean(eval(parse(text = colName))), by = grp]),
  
    # 4) works but very slow (37202ms)
    (t4 &lt;- get(dataName)[, eval(cl), by = grp]),
  
    # 5) double dot syntax doesn't work cause I don't master it
    # (t5 &lt;- get(dataName)[, mean(..colName), by = grp]),
  
    times = 10)
  </code></pre>
  <p>Is the double dot syntax appropriate here ? Why is 4) so slow ? I took it from <a href="https://stackoverflow.com/questions/27677283/evaluating-both-column-name-and-the-target-value-within-j-expression-within-d">this post</a> where it was the best option. I adapted the double dot syntax from this <a href="https://stackoverflow.com/a/12392269/13175203">post</a>.</p>
  <p>Thanks a lot for your help !</p>