Re: [R] bind mean to a df

From: baptiste auguie <baptiste.auguie_at_googlemail.com>
Date: Tue, 12 Apr 2011 15:58:10 +1200

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 <gps_at_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_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.
>



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 - 04:03:19 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