title: Function not found in R doParallel 'foreach' - Error in { : task 1 failed - "could not find function "raster""
body: <p>I am trying to use a high performance cluster at my institution for the first time and I have hit a problem that I can't resolve.</p>
  
  <p>The following code returns an error:</p>
  
  <pre><code>ptime&lt;-system.time({
    r &lt;- foreach(z = 1:length(files),.combine=cbind) %dopar% {
      raster &lt;- raster(paste(folder,files[1],sep=""))
      data&lt;-getValues(raster)
      clp &lt;- na.omit(data)
      for(i in 1:length(classes)){
        results[i,z]&lt;-length(clp[clp==classes[i]])/length(clp)
        print(z)
      }
    }
  })
  
  Error in { : task 1 failed - "could not find function "raster""
  </code></pre>
  
  <p>A also tried a different foreach code for another task I have:</p>
  
  <pre><code>r &lt;- foreach (i=1:length(poly)) %dopar% {
    clip&lt;-gIntersection(paths,poly[i,])
    lgth&lt;-gLength(clip)
    vid&lt;-poly@data[i,3]
    path.lgth[i,] &lt;- c(vid,lgth)
    print(i)
  }
  </code></pre>
  
  <p>and this time the gIntersection function isn't found. Obviously the packages are all installed and loaded. After reading some forum posts it seem it has to do with the environment that the functions execute/operate in.</p>
  
  <p>Can someone please help? I'm not a programmer!</p>
  
  <p>Thank you!</p>
  
  <p>Update:</p>
  
  <p>I have adjusted my code for the solution provided:</p>
  
  <pre><code>results&lt;-matrix(nrow=length(classes),ncol=length(files))
  dimnames(results)[[1]]&lt;-classes
  dimnames(results)[[2]]&lt;-files
  
  ptime&lt;-system.time({
      foreach(z = 1:length(files),.packages="raster") %dopar% {
      raster &lt;- raster(paste(folder,files[z],sep=""))
      data&lt;-getValues(raster)
      clp &lt;- na.omit(data)
      for(i in 1:length(classes)){
        results[i,z]&lt;-length(clp[clp==classes[i]])/length(clp)
        print(z)
      }
    }
  })
  </code></pre>
  
  <p>But what I get is an output (my results matrix) filled with na's. As you can see I create a matrix object called results to fill with results (which works with for loops), but after reading the documentation for foreach it seems that you save your results differently with this function.</p>
  
  <p>And advice on what I should choose for the .combine argument?</p>