[R] a weighted average by group

Duncan Murdoch murdoch at stats.uwo.ca
Fri Nov 18 01:47:52 CET 2005


On 11/17/2005 6:25 PM, Weiwei Shi wrote:
> Hi,
> I have a data.frame a like this:
> 
>>a
> 
>    v1 v2 v3 v4
> 1   1  1  A  X
> 2   2  2  A  X
> 3   3  3  A  X
> 4   4  4  B  X
> 5   5  5  B  X
> 6   6  6  C  Y
> 7   7  7  C  Y
> 8   8  8  C  Y
> 9   9  9  D  Y
> 10 10 10  D  Y
> 
> I want to get a weighted average for each combination of v3 and v4,
> using v1 as values and v2 as weights i.e.,
> for A and X, the final result should be (1*1+2*2+3*3)/(1+2+3)
> 
> not sure which function I should use in R ?

Use by().  For example,

by(a, list(a$v3, a$v4), function(subset) weighted.mean(subset$v1, 
subset$v2))

Duncan Murdoch




More information about the R-help mailing list