title: How to parallelise an algorithm that includes a sparse matrix, in R
body: <p>I have been using the library 'doParallel' in R to increase the speed of a set of functions. 
  However, I have run into an error that I cannot solve. I believe the following code isolates the pith of the problem:</p>
  
  <pre><code>library(Matrix)
  library(doParallel)
  
  test_mat = Matrix(c(0,1,2,NA,0,0,2,NA,1,NA,1,2,2,NA,0,1,0,2,2,2,0,0,NA,NA,1,2,1,1,2,1,rep(NA,5)), ncol=7, byrow=TRUE, sparse=TRUE)
  
  par_func &lt;- function(mat, ncores)
  {
    cl &lt;- makePSOCKcluster(ncores)
    clusterSetRNGStream(cl) 
    registerDoParallel(cl, cores = ncores)
  
    df = data.frame(1:7, NA)
  
    temp_vec = foreach(i=iter(df, by='row'), .combine=rbind) %dopar%
    {
      i[,2] &lt;- sum(mat[,i[,1]] == 1, na.rm = TRUE) + 1
    }
    stopCluster(cl)
    return(temp_vec)
  }
  
  par_func(mat=test_mat, ncores=5)
  </code></pre>
  
  <p>Which produces the following error message:</p>
  
  <pre><code>Error in { : task 1 failed - "object of type 'S4' is not subsettable" 
  </code></pre>
  
  <p>This function works if 'mat' is of class 'matrix' rather than 'dgCMatrix' so the problem appears to be due to the subsetting of a sparse Matrix. Do I have any options to work around this problem? The matrix 'mat' can be very large and can comprise many zeros, so I would like to continue to work with sparse matrices.</p>