Reputation: 135
I have two data frames.
df1 <- data.frame(cbind(c(2,3),c(4,5)))
df2 <- data.frame(cbind(c(1,2,6),c(9,8,7)))
I want to combine them and the result is like:
df3 <- data.frame(cbind(c(2,2,2,3,3,3), c(4,4,4,5,5,5),c(1,2,6,1,2,6), c(9,8,7,9,8,7)))
Is there any method to do this? Thanks.
Upvotes: 0
Views: 332
Reputation: 388817
In base R, you can use merge
and join them by NULL
to get a cartesian product of two dataframes.
merge(df1, df2, by = NULL)
# X1.x X2.x X1.y X2.y
#1 2 4 1 9
#2 3 5 1 9
#3 2 4 2 8
#4 3 5 2 8
#5 2 4 6 7
#6 3 5 6 7
Upvotes: 2
Reputation: 886938
Use crossing
library(tidyr)
crossing(df1, setNames(df2, paste0(names(df2), "_1")))
-ouptut
# A tibble: 6 x 4
X1 X2 X1_1 X2_1
<dbl> <dbl> <dbl> <dbl>
1 2 4 1 9
2 2 4 2 8
3 2 4 6 7
4 3 5 1 9
5 3 5 2 8
6 3 5 6 7
Or with expand_grid
expand_grid(df1, df2, .name_repair = "unique")
Upvotes: 0