summing matrices to a single matrix in R -


i have 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 sum of matrices element give me single matrix?

i have tried write this:-

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

but wrong. want single matrix below:-

sum:-

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

you can use apply collase on first 2 dimensions.

so if have 3x5x3 array 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)) 

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 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -