4

I have 2 data frames.
How I can make something like tidyr::complete with them using tidyverse?

My data:

df <-data.frame(a=letters[1:2] )
df1<-data.frame(one=1:2)

Expected Result:

a 1 
b 1
a 2
b 2

Thx!

jyjek
  • 2,627
  • 11
  • 23
  • Possible duplicate of [Merge two data frames with all combinations](https://stackoverflow.com/questions/37880977/merge-two-data-frames-with-all-combinations) – Saurabh Chauhan May 25 '18 at 08:09
  • are your data frames multiple columns? If yes, can you provide an example and expected results with multiple columns? – MartijnVanAttekum May 25 '18 at 08:18

3 Answers3

8

You can use tidyr::crossing

tidyr::crossing(df, df1)

# A tibble: 4 x 2
#  a       one
#  <chr> <int>
#1 a         1
#2 a         2
#3 b         1
#4 b         2

or expand_grid

tidyr::expand_grid(df, df1)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
6

With this particular example I think you can just use the merge function. As a standard its arguments all.x and all.y are set to TRUE, so it automatically creates all combinations since the dataframes do not have any variables or values in common.

df <-data.frame(a=letters[1:10] )
df1<-data.frame(one=1:10)

dfcomb <- merge(df,df1)
dim(dfcomb) 
[1] 100   2 #gives 100 rows and 2 columns
Lennyy
  • 5,932
  • 2
  • 10
  • 23
  • 1
    What R version are you using? From what I check the default parameters are `merge(all=FALSE, all.x=all, all.y=all)`. So the default is actually False, not True! – Sergej Andrejev Jan 18 '19 at 10:17
0

for your specific example, expand.grid can be used:

expand.grid(df[[1]],df1[[1]])
  Var1 Var2
1    a    1
2    b    1
3    a    2
4    b    2
MartijnVanAttekum
  • 1,405
  • 12
  • 20