[R] getting a weighted average from a table
SHANE MILLER, BLOOMBERG/ 731 LEXIN
smiller53 at bloomberg.net
Fri May 7 15:42:49 CEST 2010
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
More information about the R-help
mailing list