Home > OS >  Component-wise addition of matrices as list elements
Component-wise addition of matrices as list elements

Time:01-03

So I have a 1131 element list, with each element being a 5 by 5 matrix. The first element looks much like the other ones

sotest.corr.try[1]
[[1]]
            [,1]        [,2]       [,3]
[1,]  1.00000000 -0.04125426  0.1565728
[2,] -0.04125426  1.00000000  0.1199373
[3,]  0.15657281  0.11993733  1.0000000
[4,]  0.10209354  0.06125212  0.1937589
[5,] -0.19069820  0.17598585 -0.1235949
            [,4]        [,5]
[1,]  0.10209354 -0.19069820
[2,]  0.06125212  0.17598585
[3,]  0.19375885 -0.12359492
[4,]  1.00000000 -0.08771679
[5,] -0.08771679  1.00000000

Starting at element 126, I'd like to just add the preceding 125 matrices to 126. So that the component in the 1,2 spot, for example, would be the sum of the first 126 1,2 components. I've noticed that something like this gets what I want

sotest.corr.try[[1]] sotest.corr.try[[2]]
            [,1]        [,2]       [,3]       [,4]
[1,]  2.00000000 -0.08842164  0.3155670  0.2063603
[2,] -0.08842164  2.00000000  0.2363135  0.1156103
[3,]  0.31556697  0.23631345  2.0000000  0.3869373
[4,]  0.20636030  0.11561033  0.3869373  2.0000000
[5,] -0.38288102  0.35103362 -0.2489587 -0.1804376
           [,5]
[1,] -0.3828810
[2,]  0.3510336
[3,] -0.2489587
[4,] -0.1804376
[5,]  2.0000000

But this doesn't

sum(sotest.corr.try[[1:126]])
Error in sotest.corr.try[[1:126]] : recursive indexing failed at level 2

Is there any way to do this quickly? Maybe using lapply? Thanks

CodePudding user response:

For purposes of illustration suppose we have a list L of 5 2x2 matrices and we want the output to be the first two, followed by the cumulative sums for the others. Then

# test input
M <- matrix(1:4, 2)
L <- list(M, 2*M, 3*M, 4*M, 5*M)

ix <- 1:2
out1 <- c(L[ix], Reduce(` `, L, acc = TRUE)[-ix])

# check
out2 <- list(L[[1]], L[[2]], L[[1]]   L[[2]]   L[[3]], 
L[[1]]   L[[2]]   L[[3]]   L[[4]], L[[1]]   L[[2]]   L[[3]]   L[[4]]   L[[5]])
identical(out1, out2)
## [1] TRUE

CodePudding user response:

Here are two other options using apply or rowSums with array (borrow data from G. Grothendieck's answer)

> apply(
    array(
      do.call(
        cbind,
        L
      ), c(2, 2, length(L))
    ), 1:2, sum
  )
     [,1] [,2]
[1,]   15   45
[2,]   30   60

> rowSums(
    array(
      do.call(
        cbind,
        L
      ), c(2, 2, length(L))
    ),
    dims = 2
  )
     [,1] [,2]
[1,]   15   45
[2,]   30   60
  •  Tags:  
  • r
  • Related