[R] weighted.mean and tapply (again)

OlsenN@pac.dfo-mpo.gc.ca OlsenN at pac.dfo-mpo.gc.ca
Wed May 25 18:28:50 CEST 2005


In this simple case you can just coerce directly to a vector like so:

> foo <- by(dat, dat$GROUP, function(x) {weighted.mean(x$VALUE,
x$FREQUENCY)})
> bar <- as.vector(foo)

but look at the examples for ?by; in particular the use of 'sapply'.

Norm

-----Original Message-----
From: Dan Bolser [mailto:dmb at mrc-dunn.cam.ac.uk] 
Sent: Wednesday, May 25, 2005 9:02 AM
To: OlsenN at pac.dfo-mpo.gc.ca
Subject: RE: [R] weighted.mean and tapply (again)

On Wed, 25 May 2005 OlsenN at pac.dfo-mpo.gc.ca wrote:

>I think "by" will do what you want:
>
>> by(dat, dat$GROUP, function(x) {weighted.mean(x$VALUE, x$FREQUENCY)})
>
>Norm

Thanks Norm and Jim. My question is now...

How do you turn a <quote> list of class '"by"' </quote> into a vector of
results (one value per GROUP)?

Cheers guys!

Dan.


>
>-----Original Message-----
>From: r-help-bounces at stat.math.ethz.ch
>[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Dan Bolser
>Sent: Wednesday, May 25, 2005 8:34 AM
>To: R mailing list
>Subject: [R] weighted.mean and tapply (again)
>
>
>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 at 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
>




More information about the R-help mailing list