![](/img/trans.png)
[英]Error when using rbind to merge data.tables and one of them is empty
[英]Error when joining and assigning data.tables with one of them empty
連接和分配具有空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
不知道為什么會發生這種情況(我認為這是在單個:=
和分組的:=
的不同錯誤處理技術( ':='(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']
}
我不確定您要達到的目標,但我沒有像您一樣遇到任何錯誤
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.