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

时间:2022-10-19 23:21:21

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?

有没有办法在没有警告的情况下添加新列?

2 个解决方案

#1


25  

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; 7 characters less typing than character() but possibly less readable, depending on your preference.

顺便说一句,“”[0]是另一种创建0长度字符向量的方法;输入比字符()少7个字符但可能不太可读,具体取决于您的偏好。

#2


5  

Just as an addition how to add an empty character column, when the data.table has an arbitrary number of rows (including 0):

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

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

#1


25  

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; 7 characters less typing than character() but possibly less readable, depending on your preference.

顺便说一句,“”[0]是另一种创建0长度字符向量的方法;输入比字符()少7个字符但可能不太可读,具体取决于您的偏好。

#2


5  

Just as an addition how to add an empty character column, when the data.table has an arbitrary number of rows (including 0):

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

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