title: Combining dplyr::do() with dplyr::mutate?
body: <p>I would like to achieve the following: for each subgroup of a dataset, I would like to carry out a regression, and the residuals of that regression should be saved as a new variable in the original dataframe. For instance,</p>
  
  <pre><code> group_by(mtcars, gear) %&gt;% mutate(res = residuals(lm(mpg~carb, .)))
  </code></pre>
  
  <p>indicates what I think should work, but does not (anyone care to explain why it does not work?). One way to get the residuals is to do the following:</p>
  
  <pre><code> group_by(mtcars, gear) %&gt;% do(res = residuals(lm(mpg~carb, .)))
  </code></pre>
  
  <p>which gives me a dataframe in which <code>dbl</code>-objects are saved, i.e. those contain the residuals for each group. However, it seems they do not contain the original rownames that would help me to merge them back to the original data. </p>
  
  <p>So, my question is: how can I achieve what I want to do in a dplyr-kind of way?</p>
  
  <p>Obviously, it can be achieved in other ways. To give you an example, the following works just fine:</p>
  
  <pre><code> dat &lt;- mtcars
   dat$res &lt;- NA
   for(i in unique(mtcars$gear)){
     dat[dat$gear==i, "res"]  &lt;- residuals(lm(mpg ~ disp, data=dat[dat$gear==i,]))
   }
  </code></pre>
  
  <p>However, my understanding is that <code>dplyr</code> is made for this purpose, so there should be a <code>dplyr</code>-style way?</p>
  
  <p>Any hints / tips / comments are appreciated.</p>
  
  <p>Remark: this question is very similar to <a href="https://stackoverflow.com/questions/24766450/lm-called-within-mutate">lm() called within mutate()</a> except that in that question, only one parameter per group is retained, which makes a <code>merge</code>-approach easy. I have an entire vector with no rownames, so that I would have to rely on the ordering of the vector to do that, and that seems troublesome to me.</p>