title: Adding a column of means by group to original data
body: <p>I want to add a column of means based on factor column in <code>R</code> <code>data.frame</code>. Like this:</p>
  
  <pre><code>df1 &lt;- data.frame(X = rep(x = LETTERS[1:2], each = 3), Y = 1:6)
  df2 &lt;- aggregate(data = df1, Y ~ X, FUN = mean)
  df3 &lt;- merge(x = df1, y = df2, by = "X", suffixes = c(".Old",".New"))
  df3
  #   X Y.Old Y.New
  # 1 A     1     2
  # 2 A     2     2
  # 3 A     3     2
  # 4 B     4     5
  # 5 B     5     5
  # 6 B     6     5
  </code></pre>
  
  <p>To accomplish this problem I've to create two unnecessary <code>data.frames</code>. I'd like to know a way to append a column of means by factor column into my original <code>data.frame</code> without creating any extra <code>data.frames</code>. Thanks for your time and help.</p>