矩阵的逐元素加法作为列表元素

5

所以我有一个1131个元素的列表,每个元素都是一个5乘5矩阵。第一个元素看起来很像其他的元素。

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

从第126个元素开始,我想将前面的125个矩阵加到第126个矩阵中。例如,在1,2位置的元素将是前126个1,2位置元素的和。我注意到以下方式可以实现我的需求。
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

但这并不意味着

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

有没有快速的方法可以做到这一点?也许可以使用lapply函数?谢谢。


1
[[ is used for extracting a single list element. For multiple use [. If you need the sum of all unlist and get the sum i..e sum(unlist(sotest.corr.try)) Or if it is elementwise, use Reduce("+", sotest.corr.try[1:126]) - akrun
2个回答

3

为了举例说明,假设我们有一个包含5个2x2矩阵的列表L,并且我们希望输出前两个矩阵,然后是其余部分的累计和。

1) 我们将列表的前两个元素与使用Reduce计算出来的累积和列表的除去前两个元素的其他所有内容连接起来。

# 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

2) 一个简单的for循环也可以解决。输入L来自于(1)。

L2 <- L
for(i in seq_along(L2)[-1]) L2[[i]] <- L2[[i]] + L2[[i-1]]
ix <- 1:2
out3 <- c(L[ix], L2[-ix])

# check - out2 is from (1)
identical(out2, out3)
## [1] TRUE

2

以下是使用applyrowSumsarray的另外两个选项(从G. Grothendieck的答案中借用数据

> 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接