R中索引的多个求和

时间:2016-11-03 08:50:30

标签: r sum

我会提供一些样本数据,但我不知道如何在R中解释下面的图像。

enter image description here

我看了

Fastest way to do this double summation?

但无法根据我的问题推断答案。

1 个答案:

答案 0 :(得分:2)

您可以使用aperm并利用矢量化。你必须说明"普通"尺寸(即XC中包含的尺寸),置换X并相乘。类似的东西:

#declare which are the dimensions in X common to C
commonDims<-c(3,4)
#the other dimensions are the "uncommon" ones
uncommonDims<-setdiff(seq_along(dims),commonDims)
#then you can get the sum
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))

我们使用for循环获得的结果测试上面的结果:

set.seed(456)
dims<-c(5,6,2,3,8)
commonDims<-c(3,4)
uncommonDims<-setdiff(seq_along(dims),commonDims)
C<-array(runif(prod(dims[commonDims])),dims[commonDims])
X<-array(runif(prod(dims)),dims)
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))
#[1] 371.3749
#Calculation through loops
rsum<-0
for (i in 1:dims[1]) 
  for (j in 1:dims[2]) 
   for (k in 1:dims[3]) 
    for (r in 1:dims[4]) 
     for (t in 1:dims[5]) rsum<-rsum + X[i,j,k,r,t]*C[k,r]
rsum
#[1] 371.3749