使用来自其他 table 的值并根据其他 table 中的条件以 data.table 方式更新 table 中的值

Update value in a table with value from other table and based on condition in other table in data.table way

我有两个data.table

library(data.table)

DT1 <- data.table(
                  Part = c("A", "B", "C"),
                  Code = c(1, 3, 1),
                  PartTo = c(NA, "D", NA)
                  )

DT2 <- data.table(
                  Part = c("A", "B", "C"),
                  Info = c(1, 3, 1)
                  )

并希望根据第二个 table 的条件用第二个 table 的值更新第一个 table 中的值。

我尝试了以下方法,但它没有更新为 "D",而是更新为 NA:

DT2[DT1$Code == 3, Part := DT1$PartTo]

带有警告消息:

Warning message:
In `[.data.table`(DT2, DT1$Code == 3, `:=`(Part, DT1$PartTo)) :
Supplied 3 items to be assigned to 1 items of column 'Part' (2 unused)

结果:

    Part Info
1:    A    1
2:   NA    3
3:    C    1

感谢您的帮助!

我们可以对 'Code' 为 3 的第一个数据集进行子集化,将 on 'Part' 与 'DT2' 连接起来,然后分配 (:=) 'PartTo' 从 DT1 到 'Part'

DT2[DT1[Code==3], Part := PartTo, on = .(Part)]
DT2
#   Part Info
#1:    A    1
#2:    D    3
#3:    C    1