Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select rows from table A whose id matches those from table B, but whose (non id) values are different?

Tags:

r

data.table

Consider these two data.tables, foo and bar.

foo <- data.table(id = c(1,2,3,4), f1 = c("a", "b", "c", "d"), f2 = c("a", "b", "c", "d"))
bar <- data.table(id = c(1,2,3,4), f1 = c("a", "a", "c", "d"), f2 = c("a", "b", "c", "e"))

foo
   id f1 f2
1:  1  a  a
2:  2  b  b
3:  3  c  c
4:  4  d  d

bar
   id f1 f2
1:  1  a  a
2:  2  a  b
3:  3  c  c
4:  4  d  e

I know that foo and bar have a 1-1 relationship.

I would like to select rows from bar such that the corresponding row in foo has different values. For example,

  • id 1: the values of f1 and f2 are the same in foo and bar, so exclude this one
  • id 2: the value of f1 has changed! include this in the result
  • id 3: the values of f1 and f2 are the same in foo and bar, so exclude this one
  • id 4: the value of f2 has changed! include this in the result

Expected Result

bar[c(2,4)]
   id f1 f2
1:  2  a  b
2:  4  d  e

What I tried

I thought a non-equi join would work great here.. Unfortunately, it seems the "not equals" operator isn't supported.?

foo[!bar, on = c("id=id", "f1!=f1", "f2!=f2")]
# Invalid operators !=,!=. Only allowed operators are ==<=<>=>.

foo[!bar, on = c("id=id", "f1<>f1", "f2<>f2")]
# Found more than one operator in one 'on' statement: f1<>f1. Please specify a single operator.
like image 306
Ben Avatar asked Nov 30 '25 03:11

Ben


2 Answers

With data.table:

bar[foo,.SD[i.f1!=x.f1|i.f2!=x.f2],on="id"]

      id     f1     f2
   <num> <char> <char>
1:     2      a      b
2:     4      d      e
like image 116
Waldi Avatar answered Dec 02 '25 18:12

Waldi


I think this is best (cleanest, but perhaps not fastest?):

bar[!foo, on=.(id,f1,f2)]

      id     f1     f2
   <num> <char> <char>
1:     2      a      b
2:     4      d      e
like image 30
langtang Avatar answered Dec 02 '25 19:12

langtang