不等于data.table join中的条件

时间:2018-02-07 10:48:32

标签: r join data.table

问题

我试图加入两个表,有几个条件。我想添加一个Not Equal To条件。

我尝试了什么

我尝试使用!=和<>但什么都行不通,你知道怎么做吗?

示例

A <- data.table(c("a","a","b","c","d"),c(1,2,3,4,5),c("aa","ab","aa","cd","aa"))
B <- data.table(c("a","a","b","c","d"),c(1,1,5,4,7),c("aa","ab","aa","cd","aa"),c("yes","yes","no","yes","no"))

Jdt <- A[B,on= .(V1,V2,A.V3 != i.V3), `:=`(V4 = i.V4)][is.na(V4), V4 :=0][]

编辑所需的输出

   V1 V2 V3  V4
1:  a  1 aa   0
2:  a  2 ab yes
3:  b  3 aa  no
4:  c  4 cd   0
5:  d  5 aa  no

编辑2

我试图做这样的事情:

A[B,on=c("V1","V3"),`:=`(V42 = i.V4)][V2==i.V2,V4:="0"][,i.V2:=NULL][]

我想在加入期间重命名列,但是我收到此错误:

Error in eval(expr, envir, enclos) : object 'i.V2' not found

这里的输出我正在寻找

   V1 V2 V3  V42
1:  a  1 aa   0
2:  a  2 ab yes
3:  b  3 aa  no
4:  c  4 cd   0
5:  d  5 aa  no

1 个答案:

答案 0 :(得分:2)

您似乎实际上正在加入V1V3并检查V2上的条件。试试这个:

A[B,on=c("V1","V3")][V2==i.V2,V4:="0"][,i.V2:=NULL][]
#   V1 V2 V3  V4
#1:  a  1 aa   0
#2:  a  2 ab yes
#3:  b  3 aa  no
#4:  c  4 cd   0
#5:  d  5 aa  no