简体   繁体   中英

All Possible Pairs between Two Vectors in R Without Replacement

I'm looking to create a list of all the possible combinations of pairs between two vectors. As an example, if I have v1 = c('A', 'B', 'C') and v2 = c('X', 'Y', 'Z') , I'm NOT just looking for expand.grid(v1, v2) . I want to pair up each element of v1 with an element of v2 without replacement.

So I would want something like

AX, BY, CZ

AX, BZ, CY

AY, BX, CZ

AY, BZ, CX

AZ, BX, CY

AZ, BY, CX

Ideally, I'd love to also be able to label each combination (so AX, BY, CZ is one combination, AX, BZ, CY is the next, etc.). So the ideal output would be something like

my_df <- data.frame(
  var1 = c(A, B, C, A, B, C, A, B, C, A, B, C, A, B, C, A, B, C),
  var2 = c(X, Y, Z, X, Z, Y, Y, X, Z, Y, Z, X, Z, X, Y, Z, Y, X),
 match = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6)  
)

It seems a permutation problem, which might be solved like below

> library(pracma)

> paste0(v1, t(perms(v2)))
 [1] "AZ" "BY" "CX" "AZ" "BX" "CY" "AY" "BZ" "CX" "AY" "BX" "CZ" "AX" "BY" "CZ"
[16] "AX" "BZ" "CY"

or

out <- data.frame(
  Var1 = v1,
  Var2 = c(t(perms(v2))),
  Match = ceiling(seq(factorial(length(v2)) * length(v2)) / length(v1))
)

which gives

> out
   Var1 Var2 Match
1     A    Z     1
2     B    Y     1
3     C    X     1
4     A    Z     2
5     B    X     2
6     C    Y     2
7     A    Y     3
8     B    Z     3
9     C    X     3
10    A    Y     4
11    B    X     4
12    C    Z     4
13    A    X     5
14    B    Y     5
15    C    Z     5
16    A    X     6
17    B    Z     6
18    C    Y     6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM