简体   繁体   中英

Use of `anti_join` function in tidyverse

The book R for data science written by Hadley says that

Check that your foreign keys match primary keys in another table. The best way to do this is with an anti_join()

anti_join(x, y, by = "ID") gives rows in x that was not found in y using the ID . But I am not sure how it is going to be useful for checking whether the foreign key of one table matches the primary key of another.

Can someone provide an example?

I think the scenario the book tried to describe is the followings:

You have 2 data sets:

# data set A
# primary key is ID, foreign key is zip code

A tibble: 10 x 3
      ID zip_code   age
   <int> <chr>    <int>
 1     1 10000       43
 2     2 10001       41
 3     3 10002       46
 4     4 10003       45
 5     5 10004       50
 6     6 10005       48
 7     7 10006       40
 8     8 10007       49
 9     9 10008       44
10    10 AAAAA       42

# data set B
# primary key is zip code

 A tibble: 10 x 2
   zip_code address
   <chr>    <chr>  
 1 10000    B      
 2 10001    H      
 3 10002    U      
 4 10003    M      
 5 10004    T      
 6 10005    O      
 7 10006    P      
 8 10007    R      
 9 10008    L      
10 10009    V  

You join A and B with zip_code . In a real-world situation, there could be no matches in some rows. In this example, it is row 10 for ID = 10 .

A %>% left_join(B, by = "zip_code")

# A tibble: 10 x 4
      ID zip_code   age address
   <int> <chr>    <int> <chr>  
 1     1 10000       43 B      
 2     2 10001       41 H      
 3     3 10002       46 U      
 4     4 10003       45 M      
 5     5 10004       50 T      
 6     6 10005       48 O      
 7     7 10006       40 P      
 8     8 10007       49 R      
 9     9 10008       44 L      
10    10 AAAAA       42 NA  

What the book suggested is to use anti_join to fish out the no-matches (which could be hard to see if you have thousands of rows) and inspect the foreign key. In this example, ID = 10 has a totally different kind of foreign key which contributes to no match.

A %>% anti_join(B, by = "zip_code")

# A tibble: 1 x 3
     ID zip_code   age
  <int> <chr>    <int>
1    10 AAAAA       42

Data

library(tidyverse)
set.seed(123)

A <- tibble(ID = 1:10, zip_code = c(seq(10000, 10008, 1), "AAAAA"), age = sample(40:50, 10))

B <- tibble(zip_code =  as.character(seq(10000, 10009, 1)), address = sample(LETTERS, 10))

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