简体   繁体   English

在R中添加列以清空data.table

[英]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. 为了向现有的空data.table版本1.8.6 )添加新列,没有被警告似乎没有办法做到这一点。

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 ( "" ). 指定一个空字符向量( character() )而不是长度为1的字符向量( "" )。

> 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; 顺便说一句, ""[0]是另一种创建0长度字符向量的方法; 7 characters less typing than character() but possibly less readable, depending on your preference. 输入比character()少7个字符但可能不太可读,具体取决于您的偏好。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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