Reputation: 465
I have two 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)
)
and want to update a value in the first table with a value coming from the second table based on a condition from the second table.
I have tried the following, but it updates not to "D", but to NA:
DT2[DT1$Code == 3, Part := DT1$PartTo]
with the warning message:
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)
Result:
Part Info
1: A 1
2: NA 3
3: C 1
Thanks for any help!
Upvotes: 2
Views: 91
Reputation: 887691
We can subset the first dataset where 'Code' is 3, do a join on
the 'Part' with 'DT2', and assign (:=
) the 'PartTo' from DT1 to 'Part'
DT2[DT1[Code==3], Part := PartTo, on = .(Part)]
DT2
# Part Info
#1: A 1
#2: D 3
#3: C 1
Upvotes: 2