title: Fastest way to compute this triple summation in R
body: <p>My goal is to compute the following triple summation: </p>
  
  <pre><code>$V = \( \frac{1}{n1n2n3} \) \sum_{i=1}^{n1}\sum_{j=1}^{n2}\sum_{k=1}^{n3} I(Y_{1i},Y_{2j},Y_{3k})$
  </code></pre>
  
  <p>where I(Y1,Y2,Y3) is defined as:</p>
  
  <pre><code>I(Y1,Y2,Y3) = 1 if Y[1] &lt; Y[2] &lt; Y[3]
   I(Y1,Y2,Y3) = 1/2 if Y[1] = Y[2] &lt; Y[3]
   I(Y1,Y2,Y3) = 1/6 if Y[1] = Y[2] = Y[3]
   I(Y1,Y2,Y3) = 0 Otherwise.
  </code></pre>
  
  <p>I have implemented the calculations with R and the code is:</p>
  
  <p>The issue is that with this way the computations are so expensive.I guess that, that has to do with using <code>expand.grid()</code> to create the matrix of all combinations and then compute the Result. </p>
  
  <p>Does anyone have any more efficient way to do this? </p>
  
  <pre><code>set.seed(123)
  
  nclasses = 3
  
  ind &lt;- function(Y){
    res = 0
  
  
  if (Y[1] &lt; Y[2] &amp; Y[2] &lt; Y[3]){res = 1}
    else if (Y[1] == Y[2] &amp; Y[2] &lt; Y[3]){res = 1/2}
    else if (Y[1] == Y[2] &amp; Y[2] == Y[3]){res = 1/6}
    else {res = 0}
  
    return (res)
  }
  
  N_obs = 300
  c0 &lt;- rnorm(N_obs)
  l0 = length(c0)
  
  c1 &lt;- rnorm(N_obs)
  l1 = length(c1)
  
  c2 &lt;- rnorm(N_obs)
  l2 = length(c2)
  
  mat &lt;- matrix(unlist(t(matrix(expand.grid(c0,c1,c2)))), ncol= nclasses)
  dim(mat)
  
  Result &lt;- (1/(l0*l1*l2))*sum(apply(mat, 1, ind))
  </code></pre>