Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to empty data.table in R

Tags:

r

data.table

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?

like image 681
user1841430 Avatar asked Nov 21 '12 09:11

user1841430


People also ask

How do I add a column to a data table?

You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection.

How do I add a blank column to a data frame?

You can add an empty column to the pandas dataframe using the = operator and assign null values to the column. What is this? An empty column will be added at the end of the dataframe with the column header Empty_Column.


1 Answers

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.

like image 200
Matt Dowle Avatar answered Sep 27 '22 19:09

Matt Dowle