简体   繁体   English

连接和分配其中一个为空的data.tables时出错

[英]Error when joining and assigning data.tables with one of them empty

I ran into this error when joining and assigning columns with an empty data.table . 连接和分配具有空data.table列时遇到了此错误。 When I try to assign more than one column I get an error. 当我尝试分配多个列时,出现错误。 But assigning columns one by one is fine. 但是,一一分配列就可以了。

> 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

Not sure why it happens and how to avoid this error. 不知道为什么会发生以及如何避免此错误。 Any thought on that? 有什么想法吗?

EDIT: the version of data.table I use is 1.10.4 and R 3.4.3 编辑:版本data.table我用的是1.10.4和R 3.4.3

Not sure why it's happening (I assume it's the different error handling techniques in single := and grouped := ( ':='(x=x*z,u=x+z) )), but clearly if you change the assignee fields in the line to ones that are not present in D1, it will work. 不知道为什么会发生这种情况(我认为这是在单个:=和分组的:=的不同错误处理技术( ':='(x=x*z,u=x+z) )),但是很明显,如果您更改了受让人到D1中不存在的行中的所有字段,它将起作用。 Where NEW replaces x : 如果NEW替换x

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

You might also consider something to handle cases: 您可能还会考虑处理案件:

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

I am not exactly sure what you are trying to achieve but i have not get any ERROR as like you 我不确定您要达到的目标,但我没有像您一样遇到任何错误

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

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

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