title: All possible combinations of two vectors while keeping the order in R
body: <p>I have a vector, say <code>vec1</code>, and another vector named <code>vec2</code> as follows:</p>
  
  <pre><code>vec1 = c(4,1)
  # [1] 4 1
  
  vec2 = c(5,3,2)
  # [1] 5 3 2
  </code></pre>
  
  <p>What I'm looking for is all possible combinations of <code>vec1</code> and <code>vec2</code> while the order of the vectors' elements is kept. That is, the resultant matrix should be like this:</p>
  
  <pre><code>&gt; res
        [,1] [,2] [,3] [,4] [,5]
   [1,]    4    1    5    3    2
   [2,]    4    5    1    3    2
   [3,]    4    5    3    1    2
   [4,]    4    5    3    2    1
   [5,]    5    4    1    3    2
   [6,]    5    4    3    1    2
   [7,]    5    4    3    2    1
   [8,]    5    3    4    1    2
   [9,]    5    3    4    2    1
  [10,]    5    3    2    4    1
  
  # res=structure(c(4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 1, 5, 5, 5, 4, 4, 4, 
  # 3, 3, 3, 5, 1, 3, 3, 1, 3, 3, 4, 4, 2, 3, 3, 1, 2, 3, 1, 2, 1, 
  # 2, 4, 2, 2, 2, 1, 2, 2, 1, 2, 1, 1), .Dim = c(10L, 5L))
  </code></pre>
  
  <p>There is no repetition allowed for two vectors. That is, all rows of the resultant matrix have unique elements.</p>
  
  <p>I'm actually looking for the most efficient way. One way to tackle this problem is to generate all possible permutations of length n which grows factorially (<code>n=5</code> here) and then apply filtering. But it's time-consuming as <code>n</code> grows.</p>
  
  <p>Is there an efficient way to do that?</p>