Reputation: 261
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?
Upvotes: 26
Views: 22441
Reputation: 7113
Just as an addition how to add an empty character column, when the data.table
has an arbitrary number of rows (including 0):
DT2[ ,newcol:=character(.N) ]
Upvotes: 9
Reputation: 59602
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.
Upvotes: 35