简体   繁体   中英

Not Equal To condition in data.table join

Problem

I'm trying to join two tables, with several conditions. I would like to add a Not Equal To condition.

What I tried

I tried to use != and <> but nothing works, do you know how to do it ?

Example

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][]

EDIT Desired output

   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

EDIT 2

I'm trying to do something like this:

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

I'd like to rename the columns during the join, bu i get this error:

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

here's the output i'm looking for

   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

It seems that you are actually joining on V1 and V3 and checking conditions on V2 . Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM