在3维数组上应用weighted.mean

时间:2016-11-28 13:29:45

标签: r

我正在尝试在3维数组上应用weighted.mean。

测试数据:

set.seed(1)
arr <- array(round(runif(24, 0, 10)), c(3, 4, 2))
wgt <- matrix(round(runif(12), 1), c(3, 4))

如果只是一个卑鄙,我会这样做:

apply(arr, c(1, 3), mean)

有效,将我的(3乘4乘2)数组转换成(3乘2)矩阵,就像我想要的那样。现在我希望它是加权。而不是正常的平均值。

apply(arr, c(1, 3), weighted.mean, wgt)
Error in weighted.mean.default(newX[, i], ...) : 
  'x' and 'w' must have the same length

我想这不起作用可能是因为weighted.mean不适用于矩阵。 (我需要一个mapply或申请内的东西)。无论如何,我以为我会通过乘以先加倍然后求和来做加权均值:

apply(arr, c(1, 3), "*", wgt)
, , 1

      [,1] [,2] [,3]
 [1,]  0.9  1.2  1.8
 [2,]  3.6  0.8  3.6
 [3,]  0.0  0.0  0.0
 [4,]  0.4  0.8  0.8
 [5,]  2.7  3.6  5.4
 [6,]  2.7  0.6  2.7
 [7,]  4.5  3.5  3.0
 [8,]  0.6  1.2  1.2
 [9,]  1.5  2.0  3.0
[10,]  1.8  0.4  1.8
[11,]  7.2  5.6  4.8
[12,]  0.7  1.4  1.4

, , 2

      [,1] [,2] [,3]
 [1,]  2.1  1.2  2.4
 [2,]  2.0  2.8  4.0
 [3,]  0.0  0.0  0.0
 [4,]  0.8  2.8  0.4
 [5,]  6.3  3.6  7.2
 [6,]  1.5  2.1  3.0
 [7,]  2.0  4.0  4.5
 [8,]  1.2  4.2  0.6
 [9,]  3.5  2.0  4.0
[10,]  1.0  1.4  2.0
[11,]  3.2  6.4  7.2
[12,]  1.4  4.9  0.7

结果没有我期望的尺寸。实际上,我想:

for(i in 1:dim(arr)[3]) print(arr[,, i] * wgt)
     [,1] [,2] [,3] [,4]
[1,]  0.9  3.6  4.5  0.2
[2,]  1.6  1.8  4.2  1.6
[3,]  0.0  2.7  3.0  1.4
     [,1] [,2] [,3] [,4]
[1,]  2.1  2.0  2.0  0.4
[2,]  1.6  6.3  4.8  5.6
[3,]  0.0  3.0  4.5  0.7

最后:

> temp <- array(NA, c(3, 4, 2))
> for(i in 1:dim(arr)[3]) temp[,, i] <- arr[,, i] * wgt
> apply(temp, c(1, 3), sum)
     [,1] [,2]
[1,]  9.2  6.5
[2,]  9.2 18.3
[3,]  7.1  8.2

我已经在申请声明中尝试了所有可能的保证金排列,但都没有。

apply(arr, c(1), "*", wgt)
apply(arr, c(2), "*", wgt)
apply(arr, c(3), "*", wgt)
apply(arr, c(1, 2), "*", wgt)
apply(arr, c(1, 3), "*", wgt)
apply(arr, c(2, 3), "*", wgt)
apply(arr, c(1, 2, 3), "*", wgt)

知道什么是错的以及我如何解决它?

谢谢!

0 个答案:

没有答案