22

如何计算加权平均值R

例如,我有 4 个元素,其中 1 个元素的大小(或:长度、宽度等)为 10,3 个元素的大小为 2。

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

加权平均值为(10 * 1 + 2 * 3) / 4 = 4

4

2 回答 2

39

使用weighted.mean

> weighted.mean(z$size, z$count)
[1] 4
于 2012-06-12T00:06:28.873 回答
23

似乎您已经知道如何计算它,只需要朝着正确的方向轻推即可实现它。由于 R 是矢量化的,这非常简单:

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

with位只是节省打字,相当于sum(z$count*z$size)/sum(z$count)

weighted.mean()或者使用您还指出的内置功能。使用您自己的函数可以证明更快,但不会像内置函数那样进行相同数量的错误检查。

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
于 2012-06-12T00:18:15.163 回答