加入 data.table 子集的更新引发回收警告

Update on joined data.table subset throws recycled warning

我有两个 data.tables(称它们为 dt1 和 dt2),dt1 包含一个可以跨记录复制的 id 变量。 dt2 包含来自 dt1 的所有可能的唯一 ID 以及分配给该井调用 id2 的唯一 ID。 dt1 仅包含所有可能的 id 值的子集,而 dt2 包含整个集合。

我想用 dt2 的 id2 的匹配值更新 dt1。这让我遵循了有时有效的代码,有时它会警告我在分配 id_new.

时会回收值
dt1[ dt2, id_new := id2, nomatch = 0 ]

下面是一组可重现的代码,显示了何时有效,何时无效。

set.seed(1)
# dt_big can contain duplicate id values 
dt_big <- data.table(id    = letters[c(1,1,2,2,3,4,5,5)],
                 value = sample(8),
                 key   = "id")

# dt_small contains unique big_id values as well as it's own unique
dt_small <- data.table(id = 1:5,
                    big_id    = letters[1:5],
                       key   = "big_id")

# This works fine
dt_big[dt_small, id_new := i.id,nomatch=0]
dt_big

现在我们子集 dt_big 所以它小于 dt_small 并且 dt_big 仍然包含重复的 ids

dt_big <- data.table(id    = letters[c(1,1,2,2,3,4,5,5)],
                     value = sample(8),
                     key   = "id")
dt_big_sub_dups <- dt_big[c(1,1,5)]

# Again this works fine
dt_big_sub_dups[dt_small,id_new := i.id, nomatch=0]
dt_big_sub_dups

现在我们子 dt_big 小于 dt_small 但只包含唯一值

dt_big <- data.table(id    = letters[c(1,1,2,2,3,4,5,5)],
                     value = sample(8),
                     key   = "id")
dt_big_sub_no_dups <- dt_big[c(1,3,6)]

# Gives warning ... Supplied 3 items to be assigned to 5 items of column id_new' ...
dt_big_sub_no_dups[dt_small,id_new := i.id, nomatch=0]
dt_big_sub_no_dups

这也给出了错误的结果

   id value id_new
1:  a     7      1
2:  b     8      2
3:  d     5      1

id_new 应该 = 4 当 id="d"

使用 data.table 版本 1.9.5(和 set.seed(42)):

dt_big_sub_no_dups
#    id value id_new
# 1:  a     8      1
# 2:  b     3      2
# 3:  d     7      4