用rbind添加两个data.table的相对补码

时间:2019-02-06 12:40:40

标签: r data.table rbind

我有一个键控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

有没有那么麻烦的方法?

1 个答案:

答案 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"))