我有一个键控data.table
,我想向该键控添加另一个具有相同键的表中的行:
library(data.table)
key.cols <- c("ID", "Code")
set.seed(1)
DT1 = data.table(
ID = c("b","b","b","a","a","c"),
Code = LETTERS[seq(1,6)],
Number = runif(6)
);DT1
DT2 = data.table(
ID = c("a","a","c","b","b","b"),
Code = LETTERS[seq(4,9)],
Number = runif(6)
);DT2
我只想将DT1
中未出现的键中的DT2
行添加到DT1
行,即rbind
的相对补码:
https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement
我可以尝试使用setops
,只需添加键,让非键列填充NA
并随后加入它们:
DT1 <- rbind(DT1, fsetdiff(DT2[,(key.cols), with=FALSE], DT1[,(key.cols), with=FALSE]), fill=TRUE)
DT1[DT2, Number:=ifelse(is.na(Number), i.Number, Number), on = key.cols];DT1
有没有那么麻烦的方法?
答案 0 :(得分:4)
麻烦一点:
rbind(DT1, DT2[!DT1, on = .(ID, Code)])
ID Code Number
1: b A 0.26550866
2: b B 0.37212390
3: b C 0.57285336
4: a D 0.90820779
5: a E 0.20168193
6: c F 0.89838968
7: b G 0.06178627
8: b H 0.20597457
9: b I 0.17655675
也许更容易处理的是使用unique()
:
unique(rbind(DT1, DT2), by = c("ID", "Code"))