Hi, You could try,
library(plyr) ddply(data, .(name), transform, mean=mean(sale)) ddply(data, .(name), summarize, mean=mean(sale)) HTH, baptiste On 12 April 2011 15:46, Geoffrey Smith <g...@asu.edu> wrote: > Hello, I would like to take the mean of a column from a data frame and then > bind the mean back to the data frame. I can do this using the following > lines of code, but I am looking for a more elegant solution. Thank you very > much. Geoff > > name <- c('Frank','Frank','Frank','Tony','Tony','Tony','Ed','Ed','Ed'); > year <- c(2004,2005,2006,2004,2005,2006,2004,2005,2006); > sale <- c(56,45,55,65,68,70,45,67,23); > > data <- data.frame(name=name, year=year, sale=sale); > data; > > #is there a more elegant way to add a column of means for sale by name than > what I did below?; > > mean <- data.frame(aggregate(data$sale, list(data$name), mean)); > colnames(mean) <- c('name','mean'); > mean; > > data <- merge(data, mean); > data; > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.