将矩阵求和到R中的单个矩阵

时间:2014-06-01 21:46:46

标签: r matrix

我有以下矩阵: -

alive <- array(0,c(num_samples,num_time_periods,num_groups))
alive[,1,] <- 100  
for(i in 2:num_time_periods){
    alive[,i,] <- rbinom(num_samples, alive[,i-1,], exp(-delta[,i,]))}
alive

  , , 1

       [,1] [,2] [,3] [,4] [,5]
 [1,]  100   98   94   89   87
 [2,]  100   98   96   94   92
 [3,]  100   99   95   94   92

  , , 2

       [,1] [,2] [,3] [,4] [,5]
 [1,]  100   98   94   89   87
 [2,]  100   98   96   94   92
 [3,]  100   99   95   94   92

 , , 3

       [,1] [,2] [,3] [,4] [,5]
 [1,]  100   98   94   89   87
 [2,]  100   98   96   94   92
 [3,]  100   99   95   94   92

如何对所有矩阵元素求和,以便它给出一个矩阵?

我试着这样写: -

 Totalalive <- array(0,c(num_samples,num_time_periods,num_groups))
    for(i in 2:num_groups){
 Totalalive[,,i] <- sum(alive[,,i]) 
  }

但这是错误的。 我希望它是一个像下面这样的矩阵: -

和: -

       [,1] [,2] [,3] [,4] [,5]
 [1,]  300   294  ..   ..   ..
 [2,]  300   294  ..   ..   ..
 [3,]  300   297  ..   ..   ..

1 个答案:

答案 0 :(得分:3)

您可以使用“应用”折叠前两个维度。

因此,如果您将3x5x3数组mm作为

mm<-structure(c(0, 0, 0, 4721.565, 4721.565, 4721.565, 4244.95, 4288.055, 
4158.742, 3834.17, 3755.25, 3677.222, 3390.485, 3355.014, 3319.538, 
0, 0, 0, 4310.424, 4310.424, 4310.424, 3873.18, 3912.528, 3794.482, 
3498.017, 3425.959, 3354.792, 3092.831, 3060.493, 3028.149, 0, 
0, 0, 3934.859, 3934.859, 3934.859, 3533.586, 3569.504, 3461.75, 
3190.963, 3125.172, 3060.271, 2820.944, 2791.468, 2761.986), .Dim = c(3L, 
5L, 3L))

然后

apply(mm, c(1,2), sum)

将返回

     [,1]     [,2]     [,3]     [,4]     [,5]
[1,]    0 12966.85 11651.72 10523.15 9304.260
[2,]    0 12966.85 11770.09 10306.38 9206.975
[3,]    0 12966.85 11414.97 10092.28 9109.673