2018-11-02
阅读量:
1008
dplyr包-使用filter()筛选行
filter() 函数可以基于观测的值筛选出一个观测子集。第一个参数是数据框名称,第二个
参数以及随后的参数是用来筛选数据框的表达式。例如,我们可以使用以下代码筛选出 1
月 1 日的所有航班:
filter(flights, month == 1, day == 1)
#> # A tibble: 842 × 19
#> year month day dep_time sched_dep_time dep_delay
#> <int> <int> <int> <int> <int> <dbl>
#> 1 2013 1 1 517 515 2
#> 2 2013 1 1 533 529 4
#> 3 2013 1 1 542 540 2
#> 4 2013 1 1 544 545 -1
#> 5 2013 1 1 554 600 -6
#> 6 2013 1 1 554 558 -4
#> # ... with 836 more rows, and 13 more variables:
#> # arr_time <int>, sched_arr_time <int>, arr_delay <dbl>,
#> # carrier <chr>, flight <int>, tailnum <chr>,origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
#> # minute <dbl>, time_hour <dttm>
如果运行这行代码, dplyr 就会执行筛选操作,并返回一个新数据框。 dplyr 函数从来不修改输入,因此,如果想要保存函数结果,那么你就需要使用赋值操作符 <-:
jan1 <- filter(flights, month == 1, day == 1)
R 要么输出结果,要么将结果保存在一个变量中。如果想同时完成这两种操作,那么你可
以用括号将赋值语句括起来:
(dec25 <- filter(flights, month == 12, day == 25))
#> # A tibble: 719 × 19
#> year month day dep_time sched_dep_time dep_delay
#> <int> <int> <int> <int> <int> <dbl>
#> 1 2013 12 25 456 500 -4
#> 2 2013 12 25 524 515 9
#> 3 2013 12 25 542 540 2
#> 4 2013 12 25 546 550 -4
#> 5 2013 12 25 556 600 -4
#> 6 2013 12 25 557 600 -3
#> # ... with 713 more rows, and 13 more variables:
#> # arr_time <int>, sched_arr_time <int>, arr_delay <dbl>,
#> # carrier <chr>, flight <int>, tailnum <chr>,origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
#> # minute <dbl>, time_hour <dttm>






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
1条评论