I am trying to add an aggregated column to a data frame using dplyr. Here is an example of what I have in mind:
gender <- c("male", "female", "male")
age <- c(25, 30, 56)
weight <- c(160, 110, 220)
mydata <- data.frame(gender, age, weight)
I group the data frame mydata by gender before making an aggregated calculation to find the average weight by gender:
library(dplyr)
mydata <- group_by(mydata, gender)
mydata2 <- summarise(mydata, wt=mean(weight))
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:
SELECT gender, age, weight, avg(weight) as avg_wt FROM mydata GROUP BY gender
I realize this is a very basic question, but I am new to R and I can't seem to find the answer anywhere.