1

So I have a 3 columns that , for simplicities sake, look like this:

DF 1

ColA
A
B
C

DF 2

ColA
1
2
3

DF 3

ColC
!
@
%

My goal is I want to create a df that has every possible combination of these; I believe there will be 27 rows in the solution.

But I would like to do so using dplyr so the final dataset will looks something like this:

ColA ColB ColC
A    1    !
A    1    @
A    1    %
A    2    !
A    2    @
A    2    %
A    3    !
A    3    @
A    3    %
B    1    !
B    1    @
B    1    %

Open to using data.table here too, the real data will be in the millions in the end.

John Thomas
  • 1,075
  • 9
  • 32

2 Answers2

4

You can use tidyr's crossing or expand_grid :

tidyr::crossing(df1, df2, df3)

Or

tidyr::expand_grid(df1, df2, df3)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

No need for fancy packages, you can just use Base R's merge function:

df1 = data.frame(ColA=c("A", "B", "C"))
df2 = data.frame(ColB=1:3)
df3 = data.frame(ColC=c("!", "@", "%"))

dat = merge(df1, df2, all=TRUE)
dat = merge(dat, df3, all=TRUE)
dat
#>    ColA ColB ColC
#> 1     A    1    !
#> 2     B    1    !
#> 3     C    1    !
#> 4     A    2    !
#> 5     B    2    !
#> 6     C    2    !
#> 7     A    3    !
#> 8     B    3    !
#> 9     C    3    !
#> 10    A    1    @
#> 11    B    1    @
#> 12    C    1    @
#> 13    A    2    @
#> 14    B    2    @
#> 15    C    2    @
#> 16    A    3    @
#> 17    B    3    @
#> 18    C    3    @
#> 19    A    1    %
#> 20    B    1    %
#> 21    C    1    %
#> 22    A    2    %
#> 23    B    2    %
#> 24    C    2    %
#> 25    A    3    %
#> 26    B    3    %
#> 27    C    3    %
Vincent
  • 15,809
  • 7
  • 37
  • 39