How to do a one to one-to-many join without any keysin r using dplyr
?
I have two tables:
origin<-tribble(~"o",
1,2)
destination<-tribble(~"d",
5,
6,
7)
I want to merge both of them without any keys like the following:
od<- tribble(~"o",~"d",
1,5,
1,6,
1,7,
2,5,
2,6,
2,7)
Can anyone help me out with this?
CodePudding user response:
You can use slice
and rep
to repeat the rows in origin
based on the length of destination
. Then, inside of bind_cols
, we can create a list and repeat the values in destination
based on the length of origin
; then, bind them together.
library(tidyverse)
origin %>%
slice(rep(1:n(), each = nrow(destination[, 1]))) %>%
bind_cols(., d = unlist(rep(
c(destination[, 1]), times = nrow(origin)
)))
Output
# A tibble: 6 × 2
o d
<dbl> <dbl>
1 1 5
2 1 6
3 1 7
4 2 5
5 2 6
6 2 7
CodePudding user response:
tidyr::crossing
and expand_grid
can give you a cross join of two dataframes.
tidyr::crossing(origin, destination)
#tidyr::expand_grid(origin, destination)
# o d
# <dbl> <dbl>
#1 1 5
#2 1 6
#3 1 7
#4 2 5
#5 2 6
#6 2 7