title: R foreach could not find function "%dopar%"
body: <p>When I using the <a href="https://cran.r-project.org/web/packages/doParallel/index.html" rel="nofollow">doParallel</a> library, I encountered this weird error, the system throws this</p>
  
  <p><code>" Error in { : task 1 failed -could not find function "%dopar%"</code></p>
  
  <p>To be specific, this is what I did </p>
  
  <pre><code>library(doParallel)
  cl &lt;- makeCluster(4)
  registerDoParallel(cl)
  # Read the data
  coin95 &lt;-read.csv('~/Documents/coin95.csv')
  coin95 &lt;- coin95[,!(names(coin95) %in% c("X"))]
  coin95[c("Person")] &lt;- sapply(coin95[c("Person")],as.character)
  # create the name list
  coin95_name &lt;- as.character(coin95$Person)  
  coin95_name &lt;- unique(coin95_name)
  n &lt;- as.numeric(length(coin95_name))
  
  # the average counting process
  
  ntw &lt;- function(now){
    foreach (Ii = coin95_name,.combine = "+",.export = c("coin95","n")) %dopar% {
      time &lt;-subset(coin95, subset = coin95$Person == Ii)$duration
      stepfun(time,seq(0,length(time)))(now)/n
    }
  }
  
  # the average cumulative hazard
  lambda &lt;- function(now,params){
    b &lt;- params[1]
    sigma &lt;- params[2]
    mu &lt;- params[3]
    xi &lt;- params[4]
    beta1 &lt;- params[5]
    beta2 &lt;- params[6]
  
    k &lt;- function(spread){
      L0 &lt;- (1+(spread -mu)*xi/sigma)^(-1/xi)
      return(L0)
    }
  
    foreach(Ii = coin95_name,.combine = "+",.export = c("coin95","n")) %dopar% {
      time &lt;- subset(coin95, subset = coin95$Person == Ii)$duration
      noncov &lt;- subset(coin95, subset = coin95$Person == Ii)$noncovered
      reim &lt;- subset(coin95, subset = coin95$Person == Ii)$reimbursement
      (b*now+sum( exp(-k(now-time[(time &lt; now)])+beta1*noncov[(time &lt; now)]+beta2*reim[(time &lt;now)]) ))/n
  
    }
  
  }
  </code></pre>
  
  <p>So far, everything is GOOD, I have created two functions <code>ntw</code> and <code>lambda</code> using the <code>foreach</code>. They worked perfectly. </p>
  
  <p>Then I create the third function also using the <code>foreach</code>:</p>
  
  <pre><code># the distance
  Time &lt;- coin95$duration
  Time &lt;- sort(as.double(Time))
  
  jl &lt;- function(params){
         res&lt;-foreach(Ii = Time,.combine = "rbind",.export = c("ntw","lambda")) %dopar% {
           (ntw(Ii)-ntw(Ii-1e-7)) * (ntw(Ii)- lambda(Ii,params))^2
           }
         return(sqrt(sum(res))) 
       }
  
  guess&lt;-c(0.0,1.3333,0.0,0.1,-1.2,3e-3)
  </code></pre>
  
  <p>Type <code>jl(guess)</code>:</p>
  
  <pre><code>&gt; jl(guess)
   Show Traceback
  
   Rerun with Debug
   Error in { : task 1 failed -could not find function "%dopar%" 
  </code></pre>
  
  <p>Any Idea what's going wrong ? </p>