title: r Creating models on subsets with data.table inside a function
body: <p>Using data.table, I am trying to write a function that takes a data table, a formula object, and a string as arguments, and creates and stores multiple model objects.</p>
  
  <pre><code>myData &lt;- data.table(c("A","A","A","B","B","B"),c(1,2,1,4,5,5),c(1,1,2,5,6,4))
  ## This works.
  ModelsbyV1 &lt;- myData[,list(model=list(lm(V2~V3)),by=V1)]
  
  ##This does not.
  SectRegress &lt;- function (df,eq,sectors) {
    Output &lt;- df[,list(model=list(lm(eq))),
               by=sectors]
    return(Output)
  }
  
  Test &lt;- SectRegress(myData,formula(V2~V3),sectors="V1")
  ##Error in eval(expr, envir, enclos) : object 'X' not found
  </code></pre>
  
  <p>I have tried ataching the df in the function.  But, that nullifies the ability to group by type.  The colnames(df) inside the function includes "X".  I'm stumped. </p>