title: R: sparse matrix conversion
body: <p>I have a matrix of factors in R and want to convert it to a matrix of dummy variables 0-1 for all possible levels of each factors.</p>
  
  <p>However this "dummy" matrix is very large (91690x16593) and very sparse.  I need to store it in a sparse matrix, otherwise it does not fit in my 12GB of ram.</p>
  
  <p>Currently, I am using the following code and it works very fine and takes seconds:</p>
  
  <pre><code>library(Matrix)
  X_factors &lt;- data.frame(lapply(my_matrix, as.factor))
  #encode factor data in a sparse matrix
  X &lt;- sparse.model.matrix(~.-1, data = X_factors)
  </code></pre>
  
  <p>However, I want to use the e1071 package in R, and eventually save this matrix to libsvm format with <code>write.matrix.csr()</code>, so first I need to convert my sparse matrix to the <strong>SparseM</strong> format.</p>
  
  <p>I tried to do:</p>
  
  <pre><code>library(SparseM)  
  X2 &lt;- as.matrix.csr(X)
  </code></pre>
  
  <p>but it very quickly fills my RAM and eventually R crashes.  I suspect that internally, <code>as.matrix.csr</code> first converts the sparse matrix to a dense matrix that does not fit in my computer memory.</p>
  
  <p>My other alternative would be to create my sparse matrix directly in the SparseM format.<br>
  I tried <code>as.matrix.csr(X_factors)</code> but it does not accept a data-frame of factors.</p>
  
  <p>Is there an equivalent to <code>sparse.model.matrix(~.-1, data = X_factors)</code> in the SparseM package? I searched in the documentation but I did not find.</p>