user1783739 user1783739 - 1 month ago 8
R Question

Multiple summations over indices in R

I would have put some sample data but I do not know the first thing on how to interprete the image below in R.

enter image description here

I've looked at

Fastest way to do this double summation?

but could not extrapolate the answer there to my problem.

Answer

You can use aperm and exploit the vectorization. You must indicate which are the "common" dimensions (i.e. the dimensions contained in both X and C), permute X and multiply. Something like:

#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))

We test the result above with the one obtained with for loops:

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