R for Data Science总结之——dplyr
dplyr是R语言中一个非常流行地应用于数据处理的包,其功能包含普通SQL语言的增删改查以及统筹计算等,本文测试数据集用的是nycflights13::flights, 加载代码为:
library(dplyr)
library(nycflights13)
这里也建议直接使用Hadley Wickham的一套数据处理包tidyverse,其中包含了dplyr, purrr, tidyr, tibble, ggplot2等常用的数据处理包:
library(tidyverse)
filter()
filter()函数主要用于筛选一个数据级中满足某条件的子数据集,使用方法为:
filter(flights, month == 1, day ==1)
jan1 <- filter(flights, month == 1, day == 1)
(dec25 <- filter(flights, month == 12, day == 25))
在逻辑表达式中需注意:
sqrt(2) ^ 2 == 2
#> [1] FALSE
1 / 49 * 49 == 1
#> [1] FALSE
这是因为计算机存储的值是有限的,这里"=="不适用,推荐near()函数
near(sqrt(2) ^ 2, 2)
#> [1] TRUE
near(1 / 49 * 49, 1)
#> [1] TRUE
同时"%in%"表达式可用于表示在一个集合中,如以下代码结果是一致的:
filter(flights, month == 11 | month == 12)
nov_dec <- filter(flights, month %in% c(11, 12))
"!"表达式用于表示相反的结果,以下代码结果一致:
filter(flights, !(arr_delay > 120 | dep_delay > 120))
filter(flights, arr_delay <= 120, dep_delay <= 120)
另外对于缺失值NA,推荐使用函数is.na()进行判断,不可使用"=="等逻辑表达式
arrange()
arrange()函数可用于数据集排序,如:
arrange(flights, year, month, day)
#> # A tibble: 336,776 x 19
#> year month day dep_time sched_dep_time dep_delay arr_time
#> <int> <int> <int> <int> <int> <dbl> <int>
#> 1 2013 1 1 517 515 2 830
#> 2 2013 1 1 533 529 4 850
#> 3 2013 1 1 542 540 2 923
#> 4 2013 1 1 544 545 -1 1004
#> 5 2013 1 1 554 600 -6 812
#> 6 2013 1 1 554 558 -4 740
#> # ... with 3.368e+05 more rows, and 12 more variables:
#> # 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>