5
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.

Tomas Ericsson
  • 347
  • 1
  • 2
  • 10
  • 1
    To get all 16 combinations you can use `expand.grid(rep(list(letters[1:4]),2))`. If you don't want those where Var1 == Var2, you can use `subset(expand.grid(rep(list(letters[1:4]),2)), Var1 != Var2)` – talat Jan 14 '16 at 07:49
  • `library(gtools); permutations(length(x), 2, x, repeats = FALSE)` –  Jan 14 '16 at 07:56

3 Answers3

5

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
talat
  • 68,970
  • 21
  • 126
  • 157
4

Package gtools has a permutations function.

x <- letters[1:4]
library(gtools)
permutations(length(x), 2, x, repeats = FALSE)
#       [,1] [,2]
#  [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" 
1

Another option with dplyr/tidyr

library(dplyr)
library(tidyr)
data_frame(x1=x,x2=x) %>% 
        expand(x1, x2) %>%
        filter(x1!=x2)
#      x1    x2
#    (chr) (chr)
#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
akrun
  • 874,273
  • 37
  • 540
  • 662