title: Pass variables in function to data.table for lm()
body: <p>I want to create a function to run lm() on all data.table columns but specify the dependent (x) and by columns. The data.table, x, and by arguments are passed to the function.</p>
  
  <p>I am using David Arenburg's data.table [solution][1] with lapply() to calculate lm() and attempting to pass variables through the function with deparse() and substitute() without success.</p>
  
  <p>Below is a MWE of the desired data.table result and my function attempt, trying to pass arguments as variables and not quoted character strings.</p>
  
  <p>I believe this involves non-standard evaluation (I did read NSE in Advanced R but my understanding is not quite there).</p>
  
  <p>Any help is appreciated thanks!</p>
  
  <pre class="lang-r prettyprint-override"><code>library(data.table)
  
  set.seed(123)
  
  # Sample dataset
  data1 &lt;- data.table(colA = 1:10,
                      colB = runif(10),
                      colC = runif(10),
                      colD = rep(c("apples", "bananas"),5))
  
  # Desired functionality with .SDcols and by
  works &lt;- data1[, .(lm_results = lapply(.SD, function(x) {
    lm_summary = summary(lm(colA ~ x))})),
    .SDcols = -c("colA"),
    by = .(colD)]
  
  
  # attempted function
  fun1 &lt;- function(dt, y, by_col) {
  
    x &lt;- dt[, .(lm_results = lapply(.SD, function(x) {
      summary(lm(substitute(y) ~ x))})),
      .SDcols = -c(deparse(substitute(y)),),
      by = .(substitute(by_col))]
  
    return(x)
  }
  
  fails &lt;- fun1(data1, colA, colD)
  #&gt; Error in `[.data.table`(dt, , .(lm_results = lapply(.SD, function(x) {: column or expression 1 of 'by' or 'keyby' is type symbol. Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))]
  </code></pre>
  
  <p><sup>Created on 2019-10-16 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>