title: Replace the first zero element of a row of a matrix,
body: <p>As fast as possible, I would like to replace the first zeros in some rows of a matrix with values stored in another vector.</p>
  
  <p>There is a numeric matrix where each row is a vector with some zeros.
  I also have two vectors, one containing the rows, in what to be replaced, and another the new values: <code>replace.in.these.rows</code> and <code>new.values</code>. Also, I can generate the vector of first zeroes with sapply</p>
  
  <pre><code>mat &lt;- matrix(1,5,5)
  mat[c(1,8,10,14,16,22,14)] &lt;- 0
  replace.in.these.rows &lt;- c(1,2,3)
  new.values &lt;- c(91,92,93)
  
  corresponding.poz.of.1st.zero &lt;- sapply(replace.in.these.rows, 
                                          function(x) which(mat [x,] == 0)[1] )
  </code></pre>
  
  <p>Now I would like something that iterates over the index vectors,  but without a for loop possibly:</p>
  
  <pre><code>matrix[replace.in.these.rows, corresponding.poz.of.the.1st.zero ] &lt;- new.values 
  </code></pre>
  
  <p>Is there a trick with indexing more than simple vectors? It could not use list or array(e.g.-by-column) as index.</p>
  
  <p>By default R matrices are a set of column vectors. Do I gain anything if I store the data in a transposed form? It would mean to work on columns instead of rows.</p>
  
  <hr>
  
  <p><strong>Context</strong>:</p>
  
  <p>This matrix stores contact ID-s of a network. This is not an adjacency matrix n x n, rather n x max.number.of.partners (or n*=30)  matrix.</p>
  
  <p>The network uses edgelist by default, but I wanted to store the "all links from X" together.</p>
  
  <p>I assumed, but not sure if this is more efficient than always extract the information from the edgelist (multiple times each round in a simulation)</p>
  
  <p>I also assumed that this linearly growing matrix form is faster than storing the same information in a same formatted list.</p>
  
  <p>Some comments on these contextual assumptions are also welcome.</p>