title: Exiting loop to early or only taking one of a value if its repeated in R
body: <p>The following is some syntax relating to the problem I want to solve, but a more simplified version.</p>
  
  <p>Say I want to take all the values from one matrix and find if they exist in a specific column of another matrix then from there add them to an empty list.</p>
  
  <p>So:</p>
  
  <pre><code>mat1 &lt;- c(1,2,3)
  mat2 &lt;- matrix(c(1,2,1,2,2,2,4,21,5153,15315,21,2,2,2,2,2,2,2,2314,1,1,1,1,1), nrow =6, ncol =4, byrow = TRUE)
  
  i = 1
  j = 1
  list_final &lt;- c()
  while(i &lt; length(mat1)+1){
      if(mat2[j,2] &lt;- mat1[i]){
          list_final[j] &lt;- mat2[j,2]
          #print(list_final) 
      j=j+1
      }
      i = i+1
  }
  </code></pre>
  
  <p>Following running this, the list <code>list_final</code> is identical to <code>mat1</code>, but I want it to display:</p>
  
  <pre><code>[1] 1 2 3 2 2 1 
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <p>Just as a follow up, is it better practise to sort it during the loop or after?</p>
  
  <p>ie have an additional line after the list has been appended doing the following:</p>
  
  <p><code>[1] 1 2 3 2 2 1</code> to <code>[1] 1 1 2 2 2 3</code></p>
  
  <p>I am also trying to improve my 'elegance' where possible. Is there a way I can make this code more attractive/efficient rather than requiring two loops...</p>