Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create data.table with different size of columns

Tags:

r

data.table

I create data.table like this.

DT = data.table(A=c(1,2,3), B=c(1,2,3,4,5))

But I get this result.

   A B
1: 1 1
2: 2 2
3: 3 3
4: 1 4
5: 2 5

but I'd like to get this.

   A B
1: 1 1
2: 2 2
3: 3 3
4: NA 4
5: NA 5

How can I create data.table with different size?

like image 859
Alex808 Avatar asked Oct 03 '16 09:10

Alex808


People also ask

How do you make a table with different sized columns?

Change column and row widthSelect the rows or columns and then select Layout and choose your height and width. Select View > Ruler checkbox, select the cell you want, and then drag the markers on the ruler. Note: In Excel, select Home > Format, and then select Column Width.

How can I change the size of specific rows columns or cells in a table?

Resize rows, columns, or cells On the Layout tab, you can specify the custom height and width. To resize specific rows or column, click on a cell and then adjust the row/column. To make multiple rows or columns the same size, select the columns or rows and click Distribute Rows or Distribute Columns.


1 Answers

We keep the vector of unequal length in a list ('lst'), then loop through the list elements, append NA at the end and convert to data.table.

lst <- list(A=c(1,2,3), B=c(1,2,3,4,5))
DT <- setDT(lapply(lst, `length<-`, max(lengths(lst))))[]
DT
#    A B
#1:  1 1
#2:  2 2
#3:  3 3
#4: NA 4
#5: NA 5
like image 132
akrun Avatar answered Oct 02 '22 17:10

akrun