title: lm() within mutate() in group_by()
body: <p>I'm looking for a way to add a column to my data table that consists of <code>residuals</code> from a <code>lm(a~b)</code> function computed separately for different levels of <code>c</code></p>
  
  <p>I've been suggested to look into <code>sort_by(c)</code> function but that doesn't seem to work with <code>lm(a~b)</code></p>
  
  <p>My working example data looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/uVhz3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uVhz3.png" alt="outcome data frame"></a></p>
  
  <p>Columns subject, trial and rt are within a <code>data.frame</code>, my goal is to compute <code>Zre_SPSS</code> (that I originally made in SPSS) but from a <code>R</code> function.</p>
  
  <p>I've tried</p>
  
  <pre><code>data %&lt;&gt;% group_by (subject) %&gt;% 
    mutate(Zre=residuals(lm(log(rt)~trial)))
  </code></pre>
  
  <p>but it doesn't work - Zre gets computed but not within each subject separately, rather for the entire data frame.</p>
  
  <p>Anyone could please help me? I'm a complete R (and coding in general) newbie, so please forgive me if this question is stupid or a <a href="https://stackoverflow.com/questions/24766450/lm-called-within-mutate">duplicate</a>, chances are I didn't understand other solutions or they where not solutions I looked for. Best regards.  </p>
  
  <p>As per Ben Bolker request here is R code to generate data from excel screen shot</p>
  
  <pre><code>#generate data
    subject&lt;-c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3)
    subject&lt;-factor(subject)
    trial&lt;-c(1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6)
    rt&lt;-c(300,305,290,315,320,320,350,355,330,365,370,370,560,565,570,575,560,570)
  
  #Following variable is what I would get after using SPSS code
    ZreSPSS&lt;-c(0.4207,0.44871,-1.7779,0.47787,0.47958,-0.04897,0.45954,0.45487,-1.7962,0.43034,0.41075,0.0407,-0.6037,0.0113,0.61928,1.22038,-1.32533,0.07806)
  
  #make data frame
    sym&lt;-data.frame(subject, trial, rt, ZreSPSS)
  </code></pre>