Search code examples
rjoindata.tablecartesian

R data.table join two tables and keep all rows


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

Solution

  • 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