[R] bind mean to a df

From: Geoffrey Smith <gps_at_asu.edu>
Date: Mon, 11 Apr 2011 20:46:22 -0700

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');

data <- merge(data, mean);

        [[alternative HTML version deleted]]

R-help_at_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. Received on Tue 12 Apr 2011 - 03:49:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 12 Apr 2011 - 04:10:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive