title: foreach instead of FOR IN R
body: <p>I am a freshman of R. I want to execute randomForest in R and the data has 1000 rows and 28 columns. The idea is to test all mtry (1:27) and each of them will be tested by 10 repeats 10-fold CV. The problem is it takes such a long time and still no result! I try to use 'foreach' loop instead of 'for', but I do not know how to do it. The codes is shown below:</p>
  
  <pre><code>library(randomForest)
  n &lt;- nrow(data)
  a1 &lt;- 1:n
  a2 &lt;- rep(1:10,ceiling(n/10))[1:n]
  k &lt;- ncol(data)-1    
  trainrf &lt;- testrf &lt;- list()
  for(i in 1:k){    # tune mtry from 1 to 27
      rftrain &lt;- rftest &lt;- NULL
      for(x in 1:10){   # 10 repeats 10-fold CV
          set.seed(1981)
          a2 &lt;- sample(a2,n)
          train.rf &lt;- test.rf &lt;- rep(0,10)
          for(j in  1:10){
              m &lt;- a1[a2 == j]
              n1 &lt;- n-length(m)
              n2 &lt;- length(m)
              set.seed(2013)
              rf.data &lt;- randomForest(level~., data=data[-m,], mtry=i, ntree=1000)
              train.rf[j] &lt;- sum(data[-m,28] == predict(rf.data, data[-m,]))/n1
              test.rf[j] &lt;- sum(data[m,28] == predict(rf.data, data[m,]))/n2
          }
          rftrain[x] &lt;- mean(train.rf); rftest[x] &lt;- mean(test.rf)
      }
      trainrf[[i]] &lt;- rftrain; testrf[[i]] &lt;- rftest
  }
  </code></pre>
  
  <p>My laptop is i7 Windows 7 64-bit, and I wrote a few codes as I know:</p>
  
  <pre><code>library(foreach)
  library(doParallel)
  cl &lt;- makeCluster(4)
  registerDoParallel(cl)
  </code></pre>
  
  <p>Please help me, thanks a lot!</p>