title: ddply bug? (Adding lm residuals computed within groups back to the original data frame)
body: <p>I have a data frame with a factor (grpfactor). My goal is to compute residuals form fitting an lm model separately within each group, and store them in the original data frame.</p>
  
  <p>The model needs to be specified at run-time (i.e., cannot be a fixed string).</p>
  
  <p>I found <a href="https://stackoverflow.com/questions/20205656/run-regression-by-groups-and-assign-the-fitted-values-and-or-residuals-back-into">this answer</a> </p>
  
  <pre><code>  ddply(d,.(g1,g2),transform,z= predict(lm(y ~ x)))
  </code></pre>
  
  <p>It seems to work with a statically specified formula, but if I put the code inside a function and use a string variable instead of a string literal (constant), it fails -- why??</p>
  
  <pre><code>d &lt;- data.frame(x = rnorm(20), 
              y = rnorm(20), 
              g1 = c(rep('a', 10), rep('b', 10)), 
              g2 = rep(c(rep('c', 5), rep('d', 5)), 2))
  
  
  myfunc = function(d) {
  xx = "y ~ x"
  retval = ddply(d,.(g1,g2),transform,z= predict(lm(as.formula(xx))))
  return(retval)
  }
  
  # This fails:
  d.new = myfunc(d)
  
  # With the error:
  #Error: error in evaluating the argument 'object' in selecting a 
  #method for function 'predict': Error in as.formula(xx) : object 'xx' not 
  #found 
  
  
  # But this works, because it's not encased in a function:
  xx = "y ~ x"
  retval = ddply(d,.(g1,g2),transform,z= predict(lm(as.formula(xx))))
  
  #Now, with the variable "xx" defined two lines above this line, 
  #the following will actually work now:
  d.new = myfunc(d)
  
  #But if we do this, it will fail again:
  rm(xx)
  d.new = myfunc(d)
  
  #ddply works inside a function, but only with a model specified 
  #as a literal string:
  myfunc2 = function(d) {
  retval = ddply(d,.(g1,g2),transform,z= predict(lm(formula=as.formula("y ~ x"))))
  return(retval)
  }
  d.new2 = myfunc2(d)
  </code></pre>
  
  <p>As an aside, without as.formula, myfunc2 fails with the error:</p>
  
  <pre><code>#Error: error in evaluating the argument 'object' in selecting a method 
  #for function 'predict': Error in eval(expr, envir, enclos) : object 'y' 
  #not found
  </code></pre>
  
  <p>But the same code works without as.formula if it's not in a function.</p>
  
  <p>What is going on?  </p>
  
  <p>Edit: ok, here's where it gets really crazy: this works ( the difference is, I am defining the model in the parent environment using &lt;&lt;- )</p>
  
  <pre><code> myfunc3 = function(d) {
   xx &lt;&lt;- "y ~ x"
   retval = ddply(d,.(g1,g2),transform,z= predict(lm(as.formula(xx))))
   return(retval)
   }
   myfunc3(d)
  </code></pre>