Reputation: 179
Suppose that I have a dataframe
data.frame(v1 = c(1,1,1,2,2,3), v2 = c(6,1,6,3,4,2))
v1 v2
1 1 6
2 1 1
3 1 6
4 2 3
5 2 4
6 3 2
Is there an R function to return the following dataframe? i.e. the combinations of v2 with based on the unique values of v1
data.frame(v1 = rep(1:3, 6), v2 = c(6,3,2, 6,4,2, 1,3,2, 1,4,2, 6,3,2, 6,4,2))
v1 v2
1 1 6
2 2 3
3 3 2
4 1 6
5 2 4
6 3 2
7 1 1
8 2 3
9 3 2
10 1 1
11 2 4
12 3 2
13 1 6
14 2 3
15 3 2
16 1 6
17 2 4
18 3 2
P.S. I don't think my question is duplicated. Here v2
has duplicated values and the output dataframe has to keep the order (i.e. v1 = c(1,2,3, 1,2,3, ...)
. The desired out put has 18 rows but expand.grid
gives 36 rows and crossing
gives 15 rows
Upvotes: 1
Views: 228
Reputation: 102900
Try the code below
dfout <- data.frame(
v1 = unique(df$v1),
v2 = c(t(rev(expand.grid(rev(with(df, split(v2, v1)))))))
)
which gives
> dfout
v1 v2
1 1 6
2 2 3
3 3 2
4 1 6
5 2 4
6 3 2
7 1 1
8 2 3
9 3 2
10 1 1
11 2 4
12 3 2
13 1 6
14 2 3
15 3 2
16 1 6
17 2 4
18 3 2
Upvotes: 2