2

Have DT1, DT2; need to "join" them and keep all rows; the result is DT3. How to achieve it?

 require(data.table)
DT1 <- data.table(ID_1 = 1:2, val_1 = 1:2)
DT2 <- data.table(ID_2 = 3:4, val_2 = 3:4)

DT1
DT2

DT3 <- data.table(ID_1 = c(1,1,2,2), ID_2 = c(3,4,3,4), val_1 = c(1,1,2,2), val_2 = c(3,4,3,4))
DT3
LeGeniusII
  • 900
  • 1
  • 10
  • 28

2 Answers2

2

This is cross join assign a New Key to help merge

DT1$Key=1
DT2$Key=1
DT3=merge(DT1,DT2,by='Key')
DT3 #DT3$Key=NULL remove the key 
   Key ID_1 val_1 ID_2 val_2
1:   1    1     1    3     3
2:   1    1     1    4     4
3:   1    2     2    3     3
4:   1    2     2    4     4
BENY
  • 317,841
  • 20
  • 164
  • 234
2

We can use crossing from tidyr

tidyr::crossing(DT1, DT2)
# A tibble: 4 x 2
#  DT1$ID_1 $val_1 DT2$ID_2 $val_2
#     <int>  <int>    <int>  <int>
#1        1      1        3      3
#2        1      1        4      4
#3        2      2        3      3
#4        2      2        4      4
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213