Home > Back-end >  join each row to the whole second table in R dplyr [duplicate]
join each row to the whole second table in R dplyr [duplicate]

Time:09-18

I have two tables:

table 1:
|   | a  | b  |
|---|----|----|
| 1 | a1 | b1 |
| 2 | a2 | b2 |

and

table 2: 
|   | c  | d  |
|---|----|----|
| 1 | c1 | d1 |
| 2 | c2 | d2 |

I want to join them in a way that each row of table one bind column-wise with table two to get this result:

|   | a  | b  | c  | d  |
|---|----|----|----|----|
| 1 | a1 | b1 | c1 | d1 |
| 2 | a1 | b1 | c2 | d2 |
| 3 | a2 | b2 | c1 | d1 |
| 4 | a2 | b2 | c2 | d2 |

I feel like this is a duplicated question, but I could not find right wordings and search terms to find the answer.

CodePudding user response:

There is no need to join, we can use tidyr::expand_grid:

library(dplyr)
library(tidyr)

table1 <- tibble(a = c("a1", "a2"),
                 b = c("b1", "b2"))

table2 <- tibble(c = c("c1","c2"),
                 d = c("d1", "d2"))

expand_grid(table1, table2)
#> # A tibble: 4 x 4
#>   a     b     c     d    
#>   <chr> <chr> <chr> <chr>
#> 1 a1    b1    c1    d1   
#> 2 a1    b1    c2    d2   
#> 3 a2    b2    c1    d1   
#> 4 a2    b2    c2    d2

Created on 2021-09-17 by the reprex package (v2.0.1)

CodePudding user response:

I found a crude answer:

table1$key <- 1
table2$key <- 1
result <- left_join(table1,table2, by="key") %>%
              select(-key)

Any better answers is much appreciated.

  • Related