[英]R: Use German stopwords in tidyverse but anti_join does not work
[英]Use of `anti_join` function in tidyverse
Hadley 寫的用於數據科學的書 R 說
檢查您的外鍵是否與另一個表中的主鍵匹配。 最好的方法是使用
anti_join()
anti_join(x, y, by = "ID")
使用ID
給出x
中未在y
中找到的行。 但我不確定它對檢查一個表的外鍵是否與另一個表的主鍵匹配有什么用處。
有人可以提供一個例子嗎?
我認為這本書試圖描述的場景如下:
您有 2 個數據集:
# 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
您使用zip_code
加入 A 和 B。 在實際情況下,某些行中可能沒有匹配項。 在此示例中, ID = 10
為第 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
這本書建議使用anti_join
找出不匹配項(如果有數千行可能很難看到)並檢查外鍵。 在此示例中, ID = 10
具有完全不同類型的外鍵,導致不匹配。
A %>% anti_join(B, by = "zip_code")
# A tibble: 1 x 3
ID zip_code age
<int> <chr> <int>
1 10 AAAAA 42
數據
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.