title: Aligning like rows in a character matrix in R
body: <p>I've got a character matrix with structure like the following: </p>
  
  <pre><code>dog    1   cow    9     mouse  7 
  bird   10  tiger  1     gnu    2
  tiger  3   deer   7     deer   27
  skunk  2   rat    50    NA     NA
  mouse  8   snake  3     NA     NA 
  cow    7   NA     NA    NA     NA
  sheep  21  NA     NA    NA     NA 
  gnu    5   NA     NA    NA     NA 
  </code></pre>
  
  <p>Imagine this to be a matrix of animals in locales, with data for each locale defined by successive pairs of columns. Some animals may be common between locales, but locales may also have unique animals. Ultimately I want to make a heatmap of this data, and thus need to reorder this matrix to have a structure in which there is one column for all types animals and successive columns corresponding to numbers in each locale:</p>
  
  <pre><code>dog    1    NA    NA 
  tiger  3    1     NA 
  skunk  2    NA    NA
  mouse  8    NA    NA
  cow    7    9     NA
  sheep  21   NA    NA
  gnu    5    NA    2
  deer   NA   7     27
  rat    NA   50    NA
  snake  NA   3     NA
  mouse  NA   NA    7
  bird   10   NA    NA
  </code></pre>
  
  <p>In other words, I have</p>
  
  <pre><code>A1 &lt;- c("dog", "bird", "tiger", "skunk", "mouse", "cow", "sheep", "gnu")
  B1 &lt;- as.character(c(1, 10, 3, 2, 8, 7, 21, 5))
  A2 &lt;- c("cow", "tiger", "deer", "rat", "snake", NA, NA, NA)
  B2 &lt;- as.character(c(9, 1, 7, 50, 3, NA, NA, NA))
  A3 &lt;- c("mouse", "gnu", "deer", NA, NA, NA, NA, NA)
  B3 &lt;- as.character(c(7, 2, 27, NA, NA, NA, NA, NA))
  TheMatrix &lt;- cbind(A1, B1, A2, B2, A3, B3)
  </code></pre>
  
  <p>and want </p>
  
  <pre><code>a1 &lt;- c("dog", "tiger", "skunk", "mouse", "cow", "sheep", "gnu", "deer", "rat", "snake", "mouse", "bird")
  b1 &lt;- as.character(c(1, 3, 2, 8, 7, 21, 5, NA, NA, NA, NA, 10))
  b2 &lt;- as.character(c(NA, 1, NA, NA, 9, NA, NA, 7, 50, 3, NA, NA))
  b3 &lt;- as.character(c(NA, NA, NA, NA, NA, NA, 2, 27, NA, NA, 7, NA))
  DesiredResult &lt;- cbind(a1, b1, b2, b3)
  </code></pre>
  
  <p>Ideas on how to achieve this reorganization? It could done with loops and accounting, but surely there's a more elegant way that I'm missing. </p>