R : Triple summation over function dependent on th

2019-09-05 00:07发布

问题:

I am attempting to use R to to a triple summation over a function with three indices.

I was easily able to do this in Mathematica with the following code:

out = Sum[B[G[[k]]] * A[G[[k]], G[[j]], G[[i]]] * prod[G[[j]],G[[i]]],
          {k,1,Length[G]},{j,1,Length[G]},{i,1,Length[G]}]

where G is a matrix, and B[.], A[.], and prod[.] are all predefined functions.

In Mathematica, Sum[f,{k,k_min, k_max}, {j,j_min, j_max}, {i, i_min, i_max}] would evaluate the triple sum, Sum(k=k_min, k_max)[Sum(j=j_min, j_max)[Sum(i=i_min, i_max)[f]]], where f is some function.

I am now trying to do this in R and am having a lot of difficulty. I have tried applying sapplywith sum in the following manner, but it doesn't seem to work either.

guts.i.j.k <- function(i,j,k) B.k(k) * A.i.j.k(i, j, k) * prod.i.j(i, j)
innermostSum <- function(j,k) sum(sapply(1:length(G), FUN=guts.i.j.k, j=j, k=k ))
middleSum <- function(k) sum(sapply(1:length(G), FUN=innermostSum, k=k ))
outsideSum <- sum(sapply(1:length(G), FUN=middleSum))
return(outsideSum) 

Any help would be greatly appreciated.