title: Nested for loops in R using foreach function and doParallel library
body: <p>I am trying to calculate the cosine similarity between columns in a matrix.  I am able to get it to work using standard for loops, but when I try to make it run in parallel to make the code run faster it does not give me the same answer.  The problem is that I am unable to get the same answer using the foreach loop approach.  I suspect that I am not using the correct syntax, because I have had single foreach loops work.  I have tried to make the second loop a regular for loop and I used the <code>%:%</code> parameter with the foreach loop, but then the function doesn't even run.    </p>
  
  <p>Please see my attached code below.  Thanks in advance for any help.</p>
  
  <pre><code>## Function that calculates cosine similarity using paralel functions.
  
  #for calculating parallel processing
  library(doParallel)
  
  ## Set up cluster on 8 cores
  
  cl = makeCluster(8)
  
  registerDoParallel(cl)
  
  #create an example data
  x=array(data=sample(1000*100), dim=c(1000, 100))
  
  ## Cosine similarity function using sequential for loops
  
  cosine_seq =function (x) {
  
    co = array(0, c(ncol(x), ncol(x)))
  
    for (i in 2:ncol(x)) {
      for (j in 1:(i - 1)) {
  
        co[i, j] = crossprod(x[, i], x[, j])/sqrt(crossprod(x[, i]) * crossprod(x[, j]))
      }
    }
  
    co = co + t(co)
  
    diag(co) = 1
  
    return(as.matrix(co))
  
  }
  
  ## Cosine similarity function using parallel for loops
  
  cosine_par =function (x) {
  
    co = array(0, c(ncol(x), ncol(x)))
  
    foreach (i=2:ncol(x)) %dopar% {
  
      for (j in 1:(i - 1)) {
  
        co[i, j] = crossprod(x[, i], x[, j])/sqrt(crossprod(x[, i]) * crossprod(x[, j]))
      }
    }
  
    co = co + t(co)
  
    diag(co) = 1
  
    return(as.matrix(co))
  
  }
  
  ## Calculate cosine similarity
  
  tm_seq=system.time(
  {
  
    x_cosine_seq=cosine_seq(x)
  
  })
  
  tm_par=system.time(
  {
  
    x_cosine_par=cosine_par(x)
  
  })
  
  ## Test equality of cosine similarity functions
  
  all.equal(x_cosine_seq, x_cosine_par)
  
  #stop cluster
  stopCluster(cl)
  </code></pre>