Search code examples
rlistdata.tablerbindcbind

Binding two data.table with different length


I have a data.table that has structure like

library(data.table) #load package
a <- as.data.table(matrix(1,10,10))
b <- as.data.table(matrix(2,2,2))

As you can see, they have different dimension. I want to put together those two data.table. The result should be, first ten rows / first ten columns is "a" 11th and 12th row / 1st and 2nd column is "b"

The reason I need this is because I have a dataset(a) and a foot note(b). I would like to merge this and export it as a xlsx file. So that under the dataset lies the footnote.

I tried doing this by rbind cbind but this asks me to match the length and if i do, "b" is repeated 5 times each to match the length with "a".


Solution

  • > y <- as.data.table(matrix(1,10,10))
    
    > u <- as.data.table(matrix(2,2,2))
    
    > merge(y, u, all = TRUE)
    
        V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
     1:  1  1  1  1  1  1  1  1  1   1
     2:  1  1  1  1  1  1  1  1  1   1
     3:  1  1  1  1  1  1  1  1  1   1
     4:  1  1  1  1  1  1  1  1  1   1
     5:  1  1  1  1  1  1  1  1  1   1
     6:  1  1  1  1  1  1  1  1  1   1
     7:  1  1  1  1  1  1  1  1  1   1
     8:  1  1  1  1  1  1  1  1  1   1
     9:  1  1  1  1  1  1  1  1  1   1
    10:  1  1  1  1  1  1  1  1  1   1
    11:  2  2 NA NA NA NA NA NA NA  NA
    12:  2  2 NA NA NA NA NA NA NA  NA