[R] weighted mean and by() with two index

Frank E Harrell Jr f.harrell at vanderbilt.edu
Tue Apr 14 03:23:08 CEST 2009


Also see the help file for the wtd.mean function in the Hmisc package, 
which has an example using the summarize function to do this.

Frank

Mike Lawrence wrote:
> Sounds like a job for plyr: http://had.co.nz/plyr
> 
> 
> On Mon, Apr 13, 2009 at 7:56 PM, Dong H. Oh <r.arecibo at gmail.com> wrote:
>> Hi expeRts,
>>
>> I would like to calculate weighted mean by two factors.
>>
>> My code is as follows:
>>
>> R> tmp <- by(re$meta.sales.lkm[, c("pc", "sales")],
>>                      re$meta.sales.lkm[, c("size", "yr")], function(x)
>>                      weighted.mean(x[,1], x[,2]))
>>
>> The result is as follows:
>> R> tmp
>> size: micro
>> yr: 1994
>> [1] 1.090
>> ------------------------------------------------------------
>> size: small
>> yr: 1994
>> [1] 1.135
>> ------------------------------------------------------------
>> size: medium
>> yr: 1994
>> [1] 1.113
>> ------------------------------------------------------------
>> size: large
>> yr: 1994
>> [1] 1.105
>> ------------------------------------------------------------
>> size: micro
>> yr: 1995
>> [1] 1.167
>> ------------------------------------------------------------
>> size: small
>> yr: 1995
>> [1] 1.096
>> ------------------------------------------------------------
>> size: medium
>> yr: 1995
>> [1] 1.056
>> ....
>> ....
>>
>> But the form I want to get is as follows:
>>            1994       1995         1996      .....
>> micro    1.090      1.167         .............
>> small     1.135      1.096
>> medium 1.113      1.056        .... ........
>> large      1.105      ....... ...........
>>
>> That is, the result should be tabularized.
>> How can I get the above form directly? (I don't want to modify tmp with
>> as.vector() and matrix() to get the result)
>>
>> Thank  you in advance.
>>
>> --------------------------------------------------------------------------
>> Donghyun Oh
>> CESIS, KTH
>> --------------------------------------------------------------------------
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.
>>
> 
> 
> 


-- 
Frank E Harrell Jr   Professor and Chair           School of Medicine
                      Department of Biostatistics   Vanderbilt University




More information about the R-help mailing list