title: Creating Subset of Vector Adds Null Values
body: <p>I'm trying to create a mergeSort algorithm in R. While I <em>think</em> I have the method down, the first time I create the vector <code>e</code>, I end up with a vector of length 4 instead of 2. This causes the error below:</p>
  
  <blockquote>
    <blockquote>
      <p>"Error in if (a[2] &lt; a[1]) { : missing value where TRUE/FALSE needed"</p>
    </blockquote>
  </blockquote>
  
  <p>For some reason, R is adding an extra 2 elements to what should be a two-element vector. If anyone has an explanation for this, that would be wonderful. (Please limit advice to solving this error. I want to figure out how to do the rest on my own.)</p>
  
  <p>Code:</p>
  
  <pre><code>addLeftOver &lt;- function(buffer, array, index) {
    j &lt;- length(buffer)
    for(i in array[index:length(array)]) {
      buffer[j] = i
      print(i)
      j &lt;- j+1
    }
    return(buffer)
  }
  
  mergeSort &lt;- function(a) {
    len &lt;- length(a)
    print(a)
    print(len)
    browser()
    if(len&lt;=2) {  #base case
      if(len==1) {
        return(a)
      }
      if(a[2]&lt;a[1]) {
        return(c(a[2],a[1]))
      }
      return(a)
    }
    print(len/2)
    b &lt;- mergeSort(a[1:(len/2)])     #recursion
    e &lt;- mergeSort(a[(len/2)+1:len]) #recursion
    indexB &lt;- 1
    indexE &lt;- 1
    buffer
  
    for(i in 1:len) {
      if(e[indexC]&lt;b[indexB]) {
        buffer[index] &lt;- e[indexE]
        index &lt;- index + 1
        indexE &lt;- indexE + 1
      } else {
        buffer[index] &lt;- b[indexB]
        index &lt;- index + 1
        indexB &lt;- indexB + 1
      }
      if(indexB==len/2) {
        buffer = addLeftover(buffer, e, indexE)
        return(buffer)
      }
      if(indexE==len/2) {
        buffer = addLeftover(buffer, b, indexB)
        return(buffer)
      }
    }
  }
  
  sumArray &lt;- c(6,4,2,7,8,1,3,5)
  print(mergeSort(sumArray))
  </code></pre>
  
  <p>The <code>addLeftOver()</code> function's purpose is to copy the remnants of one of the two vectors (<code>b</code> or <code>e</code>) to the buffer when the end of the other has been reached.</p>