Add column to empty data.table in R
data.table, r
Solution
Good question. Assign an empty character vector (`character()`) rather than a length 1 character vector (`""`).
> DT = data.table(a=1:3,b=4:6)
> DT2 = DT[0]
> DT2
Empty data.table (0 rows) of 2 cols: a,b
> DT2[,newcol:=character()] # no warning
> DT2
Empty data.table (0 rows) of 3 cols: a,b,newcol
> sapply(DT2,class)
a b newcol
"integer" "integer" "character"
Btw, `""[0]` is another way to create a 0 length character vector; 7 characters less typing than `character()` but possibly less readable, depending on your preference.
Problem
For adding a new column to an existing empty data.table (version 1.8.6) there seems to be no way to do it without being warned. Example: ``` dt<-old.table[0] dt[,new_column:=""] ``` This produces the warning: ``` In '[.data.table'(dt, , ':='(new_column,"")): Supplied 1 items to be assigned to 0 items of column 'new_column' (1 unused) ``` Is there a way to add a new column without warnings?