美文网首页
R学习笔记(4):使用dplyr处理关系数据(2)

R学习笔记(4):使用dplyr处理关系数据(2)

作者: TOP生物信息 | 来源:发表于2019-04-12 00:35 被阅读0次

1. 筛选连接

  • semi_join(x, y):保留x表中与y表中的观测相匹配的所有观测
  • anti_join(x, y):丢弃x表中与y表中的观测相匹配的所有观测

半连接的使用场景:对原来的数据表进行筛选后得到了某一变量的若干个值,现在想要使用表中原来的记录来匹配这些值。
举个栗子

  1. 先将出现次数最多的10个目的地挑选出来
  2. 使用filter()实现要求
  3. 使用半连接semi_join()实现
> top_dest <- flights %>% count(dest,sort = T) %>% head(10)
> flights %>% filter(dest %in% top_dest$dest)
# A tibble: 141,145 x 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin dest  air_time distance  hour minute time_hour          
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int> <chr>   <chr>  <chr>    <dbl>    <dbl> <dbl>  <dbl> <dttm>             
 1  2013     1     1      542            540         2      923            850        33 AA        1141 N619AA  JFK    MIA        160     1089     5     40 2013-01-01 05:00:00
 2  2013     1     1      554            600        -6      812            837       -25 DL         461 N668DN  LGA    ATL        116      762     6      0 2013-01-01 06:00:00

> flights %>% semi_join(top_dest)
Joining, by = "dest" #注意上面的命令没有设置“变量”的名称,所以这里的by = "dest"是自动检索的,因为就这一个相同
# A tibble: 141,145 x 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin dest  air_time distance  hour minute time_hour          
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>    <int> <chr>   <chr>  <chr>    <dbl>    <dbl> <dbl>  <dbl> <dttm>             
 1  2013     1     1      542            540         2      923            850        33 AA        1141 N619AA  JFK    MIA        160     1089     5     40 2013-01-01 05:00:00
 2  2013     1     1      554            600        -6      812            837       -25 DL         461 N668DN  LGA    ATL        116      762     6      0 2013-01-01 06:00:00

anti_join(x, y)的用法类似。

2. 集合操作

集合操作需要x和y具有相同的变量

  • intersect(x, y):返回既在x又在y中的观测
  • union(x, y):返回x或y中的唯一观测
  • setdiff(x, y):在x中但不在y中的观测

相关文章

网友评论

      本文标题:R学习笔记(4):使用dplyr处理关系数据(2)

      本文链接:https://www.haomeiwen.com/subject/dpvfwqtx.html