在 tidyverse 中使用 `anti_join` 函数
Use of `anti_join` function in tidyverse
Hadley 写的数据科学 R 书说
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")
给出 x
中使用 ID
在 y
中找不到的行。但是我不确定它对于检查一个 table 的外键是否与另一个
的主键匹配有什么用。
有人可以举个例子吗?
我认为这本书试图描述的场景如下:
您有 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
您加入了 A 和 B zip_code
。在现实世界的情况下,某些行中可能没有匹配项。在此示例中,它是 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))
Hadley 写的数据科学 R 书说
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")
给出 x
中使用 ID
在 y
中找不到的行。但是我不确定它对于检查一个 table 的外键是否与另一个
有人可以举个例子吗?
我认为这本书试图描述的场景如下:
您有 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
您加入了 A 和 B zip_code
。在现实世界的情况下,某些行中可能没有匹配项。在此示例中,它是 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
书上建议的是使用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))