[R] weighted.mean and tapply (again)
Dan Bolser
dmb at mrc-dunn.cam.ac.uk
Wed May 25 17:33:36 CEST 2005
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.
More information about the R-help
mailing list