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
  • 45,165
  • 4
  • 35
  • 59

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.
  • 16,858
  • 11
  • 64
  • 99
0

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

Mike Williamson
  • 4,801
  • 11
  • 60
  • 93
jl5000
  • 45
  • 4