简体   繁体   中英

Add column to empty data.table in R

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?

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.

正如添加空字符列一样,当data.table具有任意行数(包括0)时:

DT2[ ,newcol:=character(.N) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM