0

I have a data frame x. I want to get the pairwise combinations of all rows, like (x[1,], x[2,), (x[1,], x[3,]), (x[2,], x[3,]). Here I take each row as an entirety. I tried functions like combn, but it gave me the combinations of all elements in all rows.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68

2 Answers2

1

I think with combn you are on the right track:

x <- data.frame(a=sample(letters, 10), b=1:10, c=runif(10), stringsAsFactors=FALSE)
ans <- combn(nrow(x), 2, FUN=function(sub) x[sub,], simplify=FALSE)

Now ans is a list of (in this case 45, in general choose(nrow(x), 2)) data.frames with two rows each.

Karsten W.
  • 17,826
  • 11
  • 69
  • 103
0

The crossing() function from the tidyr package may help you. (The link contains a StackOverflow example.)

Mike Williamson
  • 4,915
  • 14
  • 67
  • 104
jl5000
  • 45
  • 4