[R] getting a weighted average from a table

Phil Spector spector at stat.berkeley.edu
Fri May 7 17:48:36 CEST 2010


dat = c(1.3,1.2,1,3.3,3.3,5.1,1.1,1.2,0)
tt = table(dat)
sum(as.numeric(names(tt))*tt)/ sum(tt)

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu


On Fri, 7 May 2010, SHANE MILLER, BLOOMBERG/ 731 LEXIN wrote:

> Hi,
>
> I have a very simple request (I think).
> I have a vector/array,
>
>  > c <- c(1.3,1.2,1,3.3,3.3,5.1,1.1,1.2,0)
>
> I produce a reverse sorted table/histogram with it,
>
>  > t = rev(sort(table(c))
>  > t
>  c
>  3.3 1.2 5.1 1.3 1.1   1   0
>    2   2   1   1   1   1   1
>
> I would now like to get the labels "3.3 1.2 5.1 1.3 1.1   1   0"
> into its own vector and the # of counts "2   2   1   1   1   1   1"
> so I can calculate weighted averages. So if I can get the labels into
> a vector l and the counts into a vector n,
>
>  l <- c(3.3,1.2,5.1,1.3,1.1,1,0);
>  n <- c(2,2,1,1,1,1,1);
>
> for(i=0;i<7;i++)
>  total = l[i]*n[i]
> total = total / sum(n)     <- this is the weight average
>
>
>
>
>
>
> ______________________________________________
> 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