[R] Weighted Mean By Factor Using "BY"

Bill.Venables at csiro.au Bill.Venables at csiro.au
Thu Feb 24 01:10:47 CET 2011


Here is the party line, perhaps

by(data, data$TYPE, function(dat)
   with(dat, weighted.mean(MEASURE, COUNT)))


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Mike Schumacher
Sent: Thursday, 24 February 2011 9:40 AM
To: r-help at r-project.org
Subject: Re: [R] Weighted Mean By Factor Using "BY"

I withdraw this question, I was able to accomplish this by creating a new
function.

Now if only I could get the by output into a dataframe...

Mike

On Wed, Feb 23, 2011 at 2:25 PM, Mike Schumacher
<mike.schumacher at gmail.com>wrote:

> Hello R folks,
>
> Reproducible code below - I'm trying to do a weighted mean by a factor and
> can't figure it out.  Thanks in advance for your assistance.
>
> Mike
>
> data<-data.frame(c(5,5,1,1,1),
>                                 c(10,8,9,5,3),
>                                 c("A","A","A","B","B"))
>
> names(data)<-c("COUNT","MEASURE","TYPE")
>
> ## UNWEIGHTED MEAN BY TYPE
> by(data$MEASURE,data$TYPE,mean)
>
> ## WEIGHTED MEAN WITHOUT TYPE
> weighted.mean(x=data$MEASURE,w=data$COUNT)
>
> ## WEIGHTED MEAN BY TYPE - DOESNT WORK
> by(data$MEASURE,data$TYPE,weighted.mean(x=data$MEASURE,w=data$COUNT))
>
>
>
>
> --
> Michael Schumacher
> Manager, Data and Analytics
> ValueClick
> mike.schumacher at gmail.com
>
>
>
>


-- 
Michael Schumacher
mike.schumacher at gmail.com
818-851-8638

	[[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.



More information about the R-help mailing list