5. 过滤连接
过滤连接与可变连接匹配观察值的方式相同,但是会影响观察值,而不影响变量。
分为两种类型:
-
semi_join(x, y)
:保留x
中所有与y
匹配的观察值 -
anti_join(x, y)
:删除x
中所有与y
匹配的观察值
semi_join
对于将筛选后的汇总表与原始数据进行匹配非常有用。
例如,您想要找到了人流量最多的十大目的地:
> top_dest <- flights %>%
+ count(dest, sort = TRUE) %>%
+ head(10)
> top_dest
# A tibble: 10 x 2
dest n
<chr> <int>
1 ORD 17283
2 ATL 17215
3 LAX 16174
4 BOS 15508
5 MCO 14082
6 CLT 14064
7 SFO 13331
8 FLL 12055
9 MIA 11728
10 DCA 9705
现在,您想要查找去往那些目的地之一的航班
> flights %>%
+ filter(dest %in% top_dest$dest) %>%
+ head(5)
# A tibble: 5 x 19
year month day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight
<int> <int> <int> <int> <int> <dbl> <int> <int> <dbl> <chr> <int>
1 2013 1 1 542 540 2 923 850 33 AA 1141
2 2013 1 1 554 600 -6 812 837 -25 DL 461
3 2013 1 1 554 558 -4 740 728 12 UA 169