user3680646
user3680646

Reputation: 3

summing matrices to a single matrix in R

I have the following matrices:-

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

How do i sum all of the matrices element so that it will give me a single matrix?

I have tried to write like this:-

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

But it is wrong. I want it to be a single matrix like below:-

Sum:-

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

Upvotes: 0

Views: 84

Answers (1)

MrFlick
MrFlick

Reputation: 206232

You can use apply to collase over the first two dimensions.

So if you have your 3x5x3 array mm as

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))

Then

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

will return

     [,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

Upvotes: 3

Related Questions