Dinesh.hmn - 1 month ago 21

R Question

I have a data frame as

`df <- data.frame(x = c(1,2,3,4,5), y = c(11,12,13,14,15))`

What I am trying to get is this

`df`

1 11

2 12

3 13

4 14

5 15

2 12

3 13

4 14

5 15

3 13

4 14

5 15

5 15

It basically is all the possible combinations of the data frame. I tried combn and expand.grid but they give me all possible combinations, not all possible combinations taken two at a time. I also tried looping it but the subsetting always goes for a toss.

Any ideas?

Answer

We can sequence by the pairs with an `sapply`

iteration. Then binding the vectors with the index:

```
df <- data.frame(x = c(1,2,3,4,5), y = c(11,12,13,14,15))
s <- seq(length(df$x))
d2 <- unlist(sapply(s, seq, to=max(s)))
cbind.data.frame(x=df$x[d2], y=df$y[d2])
# x y
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15
# 6 2 12
# 7 3 13
# 8 4 14
# 9 5 15
# 10 3 13
# 11 4 14
# 12 5 15
# 13 4 14
# 14 5 15
# 15 5 15
```