2
x = 1:3
y = 1:3
> expand.grid(x = 1:3, y = 1:3)
  x y
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
6 3 2
7 1 3
8 2 3
9 3 3

Using expand.grid gives me all of the combinations. However, I want only pairwise comparisons, that is, I don't want a comparison of 1 vs 1, 2 vs, 2, or 3 vs 3. Moreover, I want to keep only the unique pairs, i.e., I want to keep 1 vs 2 (and not 2 vs 1).

In summary, for the above x and y, I want the following 3 pairwise combinations:

  x y
1 1 2
2 1 3
3 2 3

Similarly, for x = y = 1:4, I want the following pairwise combinations:

  x y
1 1 2
2 1 3
3 1 4
4 2 3
5 2 4
6 3 4
Adrian
  • 9,229
  • 24
  • 74
  • 132

3 Answers3

5

We can use combn

f1 <- function(x) setNames(as.data.frame(t(combn(x, 2))), c("x", "y"))
f1(1:3)
#   x y
#1 1 2
#2 1 3
#3 2 3

f1(1:4)
#  x y
#1 1 2
#2 1 3
#3 1 4
#4 2 3
#5 2 4
#6 3 4
akrun
  • 874,273
  • 37
  • 540
  • 662
4

Using data.table,

library(data.table)

x <- 1:4
y <- 1:4

CJ(x, y)[x < y]
   x y
1: 1 2
2: 1 3
3: 1 4
4: 2 3
5: 2 4
6: 3 4
Ben
  • 20,038
  • 30
  • 112
  • 189
4

Actually you are already very close to the desired output. You may need subset as well

> subset(expand.grid(x = x, y = y), x < y)
  x y
4 1 2
7 1 3
8 2 3

Here is another option but with longer code

v <- letters[1:5] # dummy data vector
mat <- diag(length(v))
inds <- upper.tri(mat)
data.frame(
  x = v[row(mat)[inds]],
  y = v[col(mat)[inds]]
)

which gives

   x y
1  a b
2  a c
3  b c
4  a d
5  b d
6  c d
7  a e
8  b e
9  c e
10 d e
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81