title: Calculate the mean per subject and repeat the value for each subject's row
body: <p>This is the first time that I ask a question on stack overflow. I have tried searching for the answer but I cannot find exactly what I am looking for. I hope someone can help.</p>
  
  <p>I have a huge data set of 20416 observation. Basically, I have 83 subjects and for each subject I have several observations. However, the number of observations per subject is not the same (e.g. subject 1 has 256 observations, while subject 2 has only 64 observations).
  I want to add an extra column containing the mean of the observations for each subject (the observations are reading times (RT)).</p>
  
  <p>I tried with the aggregate function: </p>
  
  <pre><code>aggregate (RT ~ su, data, mean)
  </code></pre>
  
  <p>This formula returns the correct mean per subject. But then I cannot simply do the following:</p>
  
  <pre><code>data$mean &lt;- aggregate (RT ~ su, data, mean)
  </code></pre>
  
  <p>as R returns this error:</p>
  
  <blockquote>
    <p>Error in $&lt;-.data.frame(<em>tmp</em>, "mean", value = list(su = 1:83, RT
    = c(378.1328125,  : replacement has 83 rows, data has 20416</p>
  </blockquote>
  
  <p>I understand that the formula lacks a command specifying that the mean for each subject has to be repeated for all the subject's rows (e.g. if subject 1 has 256 rows, the mean for subject 1 has to be repeated for 256 rows, if subject 2 has 64 rows, the mean for subject 2 has to be repeated for 64 rows and so forth).</p>
  
  <p>How can I achieve this in R?</p>