r中多个矩阵的累积和

时间:2016-09-05 15:08:32

标签: r matrix

假设我有一个由3个矩阵组成的数组。

set.seed(1)
array1<-array(sample(1:50,18), dim=c(2,3,3))
, , 1
     [,1] [,2] [,3]
[1,]   14   28   10
[2,]   19   43   41
, , 2
     [,1] [,2] [,3]
[1,]   42   27    9
[2,]   29    3    7
, , 3
     [,1] [,2] [,3]
[1,]   44   48   25
[2,]   15   18   33

我需要的是两个矩阵式累积矩阵,一个是前两个矩阵的和,另一个是三个矩阵的总和。显然,我可以通过计算两个矩阵的总和得到它们,如下所示。

array1[,,1]+array1[,,2]
     [,1] [,2] [,3]
[1,]   56   55   19
[2,]   48   46   48

array1[,,1]+array1[,,2]+array1[,,3]
     [,1] [,2] [,3]
[1,]  100  103   44
[2,]   63   64   81

但是,我想知道一种在有很多矩阵的情况下用简单函数生成累积矩阵的方法。

感谢。

2 个答案:

答案 0 :(得分:2)

我们可以将applyMARGIN一起使用并获取sum

apply(array1[,,1:2], c(1,2), sum)
#     [,1] [,2] [,3]
#[1,]   56   55   19
#[2,]   48   46   48

apply(array1, c(1,2), sum)
#     [,1] [,2] [,3]
#[1,]  100  103   44
#[2,]   63   64   81

或者我们指定MARGIN=1并获取rowSums

t(apply(array1[,, 1:2], 1, rowSums))
t(apply(array1, 1, rowSums))

或者另一个选项是初始化输出矩阵后的for循环(&#39; r2&#39;)

r2 <- matrix(0, nrow = nrow(array1[,,1]), ncol = ncol(array1[,,1]))
for(j in seq(dim(array1)[3])){
     r2 <- r2 + array1[,,j]
 }
r2
#    [,1] [,2] [,3]
#[1,]  100  103   44
#[2,]   63   64   81

对于第一种情况,请在seq(dim(array1)[3])循环中使用head(seq(dim(array1)[3]),2)而不是for

答案 1 :(得分:2)

为了给你的具体例子添加akrun的方法,在数组中创建和求和的函数形式将是:

set.seed(1)
SumMatrices<-function(beginSum,endSum,n){
matrixArray<-array(sample(1:50,6*n), dim=c(2,3,n)) 
#where 6 is the product of the first two dimensions - 2*3,
#and 1:50 are the limits of the random number generation
apply(matrixArray[,,beginSum:endSum], c(1,2), sum)
#beginSum and endSum are the matrices within the array you would
#like to sum
}
SumMatrices(1,2,3)

当然,这也可以推广,因此用户可以将数组中的矩阵设置为他们想要的任何维度:

set.seed(1)
SumMatrices<-function(beginSum,endSum,x,y,n){
matrixArray<-array(sample(1:50,x*y*n), dim=c(x,y,n)) 
apply(matrixArray[,,beginSum:endSum], c(1,2), sum)
}
SumMatrices(1,2,2,3,3)

希望这能回答你的问题!