[R] weighted.mean and tapply (again)

From: Dan Bolser <dmb_at_mrc-dunn.cam.ac.uk>
Date: Thu 26 May 2005 - 01:33:36 EST

I read answers to questions including the words "tapply" and "weighted.mean", but I didn't understand either the problem (data) or the solution provided.

Here is my question ...

> dat[1:10,]

  GROUP VALUE FREQUENCY

1     2      2        78
2     2      3        40
3     2      4        16
4     2      5         3
5     2      6         1
6     2      8         1
7     3      3        19
8     3      4        10
9     3      5        19
1     3      6         4


For each GROUP, I would like to calculate the weighted.mean of VALUE using the FREQUENCY as the weight, so for the snippet of data shown that would be...

group.2 <- weighted.mean(c(2,3,4,5,6,8),c(78,40,16,3,1,1)) group.3 <- weighted.mean(c(3,4,5,6), c(19,10,19,4))

> cbind(rbind(2,3),rbind(group.2,group.3))

        [,1] [,2]
group.2 2 2.654676
group.3 3 4.153846

I would like to use tapply to automatically do this across the whole dataset (dat) - which includes lots of other distinct grouping factors, however, like I said, I couldn't understand (and therefore apply to my data) any of the other solutions I found, so any help here would be greatly appreciated!

All the best,
Dan.



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu May 26 01:38:34 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:05 EST