Reorder rows of a matrix by a vector containing an incomplete index
<p>I have a matrix of data:</p>

<pre><code>&gt; matrix &lt;- matrix(rnorm(16), ncol=4)
&gt; matrix
           [,1]       [,2]       [,3]        [,4]
[1,] -0.9239653  0.4217107 -0.3092167  0.09732866
[2,] -0.9635737  0.3755872 -0.4033848  1.67775919
[3,]  1.1193376 -0.3618842 -1.0036277 -0.50638047
[4,] -0.2659838 -0.8215967  0.1611249 -0.05114933
</code></pre>

<p>I want to re-order the rows of the matrix by an index specified in a vector. If the numbers in the index correspond to row numbers in the matrix, this is easy:</p>

<pre><code>&gt; index &lt;- c(3, 2, 1, 4)
&gt; reordered.matrix &lt;- matrix[index, ]
&gt; reordered.matrix
           [,1]       [,2]       [,3]        [,4]
[1,]  1.1193376 -0.3618842 -1.0036277 -0.50638047
[2,] -0.9635737  0.3755872 -0.4033848  1.67775919
[3,] -0.9239653  0.4217107 -0.3092167  0.09732866
[4,] -0.2659838 -0.8215967  0.1611249 -0.05114933
</code></pre>

<p>However, in real life my index contains some zeros. These zeros specify positions where I want to discard the data, i.e. to just have a row of zeros or NAs in that row. Here is what I would like to get:</p>

<pre><code>&gt; index &lt;- c(3, 0, 1, 0)
&gt; reordered.matrix &lt;- matrix[index, ]
&gt; reordered.matrix
           [,1]       [,2]       [,3]        [,4]
[1,]  1.1193376 -0.3618842 -1.0036277 -0.50638047
[2,]          0          0          0           0  
[3,] -0.9239653  0.4217107 -0.3092167  0.09732866
[4,]          0          0          0           0
</code></pre>

<p>But instead R ignores the zeroes, and i just get:</p>

<pre><code>           [,1]       [,2]       [,3]        [,4]
[1,]  1.1193376 -0.3618842 -1.0036277 -0.50638047
[2,] -0.9239653  0.4217107 -0.3092167  0.09732866
</code></pre>

<p>A possible solution would be to write a loop that goes though the index on-by-one, copies the data and writes it to the correct position on a new matrix. However, the matrices I am using are huge (millions of rows) and loops are way too slow. Is there any way I can get what I want without resorting to a loop?</p>