title: Vectorise R code to randomly select 2 columns from each row
body: <p>Does anyone have suggestions of how I could vectorise this code or otherwise speed it up? I'm creating a matrix, potentially very large. In each row, I want to select 2 columns at random, and flip them from 0 to 1.</p>
  
  <p>I cannot select the same row and column number, i.e. the diagonal of the matrix will be zero hence the <code>(1:N)[-j]</code> in <code>sample()</code>. Because this changes with each row, I can't see a way to do this by using vectorisation, but parallelisation could be an option here?</p>
  
  <p>I use <code>library(Matrix)</code> for sparse matrix functionality.</p>
  
  <pre><code>library(Matrix)
  N &lt;- 100
  m &lt;- Matrix(0, nrow = N, ncol = N)
  
  for(j in 1:N) {
      cols &lt;- sample((1:N)[-j], 2) #Choose 2 columns not equal to the 
      m[j, cols] &lt;- 1
  }
  </code></pre>
  
  <p>Any ideas?</p>