简体   繁体   中英

How to compute weighted mean in R?

How do I compute the weighted mean in R ?

For example, I have 4 elements of which 1 element is of size (or: length, width, etc.) 10 and 3 elements are of size 2.

> z = data.frame(count=c(1,3), size=c(10,2))
> z
  count size
1     1   10
2     3    2

The weighted average is (10 * 1 + 2 * 3) / 4 = 4 .

Use weighted.mean :

> weighted.mean(z$size, z$count)
[1] 4

Seems like you already know how to calculate this, just need a nudge in the right direction to implement it. Since R is vectorized, this is pretty simple:

with(z, sum(count*size)/sum(count))

The with bit just saves on typing and is equivalent to sum(z$count*z$size)/sum(z$count)

Or use the built in function weighted.mean() as you also pointed out. Using your own function can prove faster, though will not do the same amount of error checking that the builtin function does.

builtin <- function() with(z, weighted.mean(count, size))
rollyourown <- function() with(z, sum(count*size)/sum(count))

require(rbenchmark)  
  benchmark(builtin(), rollyourown(),
            replications = 1000000,
            columns = c("test", "elapsed", "relative"),
            order = "relative")
#-----
           test elapsed relative
2 rollyourown()   13.26 1.000000
1     builtin()   22.84 1.722474

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM