加入并分配data.tables时出错,其中一个为空

时间:2018-04-02 09:58:31

标签: r data.table

我在加入并分配空data.table的列时遇到此错误。当我尝试分配多个列时,我收到错误。但是逐个分配列很好。

> D1 <- data.table(l = "a", x = 0)
> D2 <- data.table(l = character(0), z = numeric(0))
> D1[D2, `:=`(x = x + z, u = x * z), on = "l"] ## Error

Error in `[.data.table`(D1, D2, `:=`(x = x + z, u = x * z), on = "l") : 
RHS of assignment to existing column 'x' is zero length but not NULL. 
If you intend to delete the column use NULL. Otherwise, the RHS must 
have length > 0; e.g., NA_integer_. If you are trying to change the 
column type to be an empty list column then, as with all column type 
changes, provide a full length RHS vector such as 
vector('list',nrow(DT)); i.e., 'plonk' in the new column

> D1[D2, u := x * z, on = "l"] ## Fine
> D1[D2, x := x + z, on = "l"] ## Fine

不确定为什么会发生以及如何避免此错误。有什么想法?

编辑:我使用的data.table版本是1.10.4和R 3.4.3

2 个答案:

答案 0 :(得分:1)

不确定为什么会发生这种情况(我认为这是单:=中不同的错误处理技术并且分组为:=':='(x=x*z,u=x+z))),但显然如果您更改了受理人字段线路到D1中不存在的线路,它将起作用。 NEW替换x的地方:

D1[D2, ':='(NEW = x + z, u = x * z), on = 'l']

您可能还会考虑处理案件:

if (nrow(D1[D2, on = 'l']) == 0) {
  D1[, ':='(x = NA, u = NA)]
} else {
  D1[D2, ':='(x = x + z, u = x * z), on = 'l']
}

答案 1 :(得分:0)

我不确定你想要达到的目的但我没有像你一样得到任何错误

 varr= [code(0), code(1), code(2), code(3)]