All possible combinations of two vectors while maintaining the order in R

I have a vector that says vec1, and another vector vec2 is as follows:

vec1 = c(4,1)
# [1] 4 1

vec2 = c(5,3,2)
# [1] 5 3 2

I'm looking for all possible combinations of vec1 and vec2 while maintaining the order of vector elements In other words, the resulting matrix should be as follows:

> 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,5,1,# 3,2,# 2,1),.Dim = c(10L,5L))

Two vectors cannot be repeated That is, all rows of the resulting matrix have unique elements

I'm actually looking for the most effective way One way to solve this problem is to generate all possible permutations of length n (n = 5) and then apply filtering However, as n increases, it is time consuming

Is there any way to do this?

Solution

Try this:

nv1 <- length(vec1)
nv2 <- length(vec2)
n <- nv1 + nv2

result <- combn(n,nv1,function(v) {z=integer(n);z[v]=vec1;z[-v]=vec2;z})

The idea is to generate all combined indexes to place the elements of vec1

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>