[R] getting a weighted average from a table
David Winsemius
dwinsemius at comcast.net
Fri May 7 16:16:34 CEST 2010
On May 7, 2010, at 9:42 AM, 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"
> names(t)
[1] "3.3" "1.2" "5.1" "1.3" "1.1" "1" "0"
> as.numeric(names(t))
[1] 3.3 1.2 5.1 1.3 1.1 1.0 0.0
> unname(t)
[1] 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list