Search code examples
rcombn

Possible combinations of a vector with respect order


x <- letters[1:4]
x
# [1] "a" "b" "c" "d"

t(combn(x, 2))
#   [,1] [,2]
# [1,] "a"  "b" 
# [2,] "a"  "c" 
# [3,] "a"  "d" 
# [4,] "b"  "c" 
# [5,] "b"  "d" 
# [6,] "c"  "d" 

How should I write the code if I also what inverse combinations with b-a, c-a...d-c. 12 combinations in total.


Solution

  • You can make use of expand.grid from base R to get all possible combinations of the vector (i.e. 16 combinations) and then use subset (or [.data.frame) so that the values in both columns are never equal in a row (resulting in the expected 12 combinations):

    x <- letters[1:4]
    subset(expand.grid(rep(list(x),2)), Var1 != Var2)
    #   Var1 Var2
    #2     b    a
    #3     c    a
    #4     d    a
    #5     a    b
    #7     c    b
    #8     d    b
    #9     a    c
    #10    b    c
    #12    d    c
    #13    a    d
    #14    b    d
    #15    c    d
    

    An alternative with data.table's cross-join (CJ) function:

    libraray(data.table)
    CJ(x, x)[V1 != V2]
    #    V1 V2
    # 1:  a  b
    # 2:  a  c
    # 3:  a  d
    # 4:  b  a
    # 5:  b  c
    # 6:  b  d
    # 7:  c  a
    # 8:  c  b
    # 9:  c  d
    #10:  d  a
    #11:  d  b
    #12:  d  c