Adding an aggregated column to a data frame using dplyr
<p>I am trying to add an aggregated column to a data frame using dplyr. Here is an example of what I have in mind:</p>

<pre><code>gender &lt;- c("male", "female", "male")
age &lt;- c(25, 30, 56)
weight &lt;- c(160, 110, 220)
mydata &lt;- data.frame(gender, age, weight)
</code></pre>

<p>I group the data frame <strong>mydata</strong> by gender before making an aggregated calculation to find the average weight by gender:</p>

<pre><code>library(dplyr)
mydata &lt;- group_by(mydata, gender)
mydata2 &lt;- summarise(mydata, wt=mean(weight))
</code></pre>

<p>Is there any way of adding the column of average weight to the original data frame in the same step as above? In SQL, I would achieve this using the following line of code:</p>

<pre><code>SELECT gender, age, weight, avg(weight) as avg_wt FROM mydata GROUP BY gender
</code></pre>

<p>I realize this is a very basic question, but I am new to R and I can't seem to find the answer anywhere.</p>