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.
Asked
Active
Viewed 81 times
0

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

Yao Tong
- 1
-
1Something like `expand.grid(1:2, 1:2)`? – Maurits Evers Feb 27 '18 at 22:57
-
2Post a [MCVE]. Refer to "How to make a Great Reproducible Example" https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – IRTFM Feb 27 '18 at 23:01
2 Answers
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