R Select()、Filter()、Arrange()、Pipeline 结合示例

dplyr库包含有价值的动词来导航数据集。通过本教程,您将使用“行程时间”数据集。该数据集收集了司机在家和工作地点之间通勤的信息。数据集中有十四个变量,包括

  • DayOfWeek:识别司机使用汽车的星期几
  • Distance:行程总距离
  • MaxSpeed:行程最高速度
  • TotalTime:行程时长(分钟)

该数据集约有 200 个观测值,行程发生在周一至周五之间。

首先,您需要

  • 加载数据集
  • 检查数据结构。

dplyr 的一个便捷功能是 glimpse() 函数。这是对 str() 的改进。我们可以使用 glimpse() 查看数据集结构并决定需要进行哪些操作。

library(dplyr) 
PATH <- "https://raw.githubusercontent.com/guru99-edu/R-Programming/master/travel_times.csv"
df <- read.csv(PATH)
glimpse(df)

输出

## Observations: 205
## Variables: 14
## $ X              <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...
## $ Date           <fctr> 1/6/2012, 1/6/2012, 1/4/2012, 1/4/2012, 1/3/20...
## $ StartTime      <fctr> 16:37, 08:20, 16:17, 07:53, 18:57, 07:57, 17:3...
## $ DayOfWeek      <fctr> Friday, Friday, Wednesday, Wednesday, Tuesday,...
## $ GoingTo        <fctr> Home, GSK, Home, GSK, Home, GSK, Home, GSK, GS...
## $ Distance       <dbl> 51.29, 51.63, 51.27, 49.17, 51.15, 51.80, 51.37...
## $ MaxSpeed       <dbl> 127.4, 130.3, 127.4, 132.3, 136.2, 135.8, 123.2...
## $ AvgSpeed       <dbl> 78.3, 81.8, 82.0, 74.2, 83.4, 84.5, 82.9, 77.5,...
## $ AvgMovingSpeed <dbl> 84.8, 88.9, 85.8, 82.9, 88.1, 88.8, 87.3, 85.9,...
## $ FuelEconomy    <fctr> , , , , , , -, -, 8.89, 8.89, 8.89, 8.89, 8.89...
## $ TotalTime      <dbl> 39.3, 37.9, 37.5, 39.8, 36.8, 36.8, 37.2, 37.9,...
## $ MovingTime     <dbl> 36.3, 34.9, 35.9, 35.6, 34.8, 35.0, 35.3, 34.3,...
## $ Take407All     <fctr> No, No, No, No, No, No, No, No, No, No, No, No...
## $ Comments       <fctr> , , , , , , , , , , , , , , , Put snow tires o...	

很明显,Comments 变量需要进一步诊断。Comments 变量的第一个观测值全为缺失值。

sum(df$Comments =="")

代码解释

  • sum(df$Comments ==””): 计算 df 中 comments 列等于 “” 的观测值总数

输出

## [1] 181

select()

我们将从 select() 动词开始。我们不一定需要所有变量,而且一个好的做法是只选择您认为相关的变量。

我们有 181 个缺失观测值,占数据集的近 90%。如果您决定排除它们,将无法继续分析。

另一种选择是使用 select() 动词删除 Comment 变量。

我们可以用不同的方式用 select() 选择变量。请注意,第一个参数是数据集。

- `select(df, A, B ,C)`: Select the variables A, B and C from df dataset.
- `select(df, A:C)`: Select all variables from A to C from df dataset.
- `select(df, -C)`: Exclude C from the dataset from df dataset.	

您可以使用第三种方式排除 Comments 变量。

step_1_df <- select(df, -Comments)
dim(df)

输出

## [1] 205  14
dim(step_1_df)

输出

## [1] 205  13

原始数据集有 14 个特征,而 step_1_df 有 13 个。

Filter()

filter() 动词有助于保留符合标准的观测值。filter() 的工作方式与 select() 完全相同,先传递数据框,然后通过逗号分隔条件

filter(df, condition)
arguments:
- df: dataset used to filter the data
- condition:  Condition used to filter the data	

一个标准

首先,您可以计算因子变量每个级别中的观测值数量。

table(step_1_df$GoingTo)

代码解释

  • table(): 按级别计数观测值。注意,只接受因子级别变量
  • table(step_1_df$GoingTo): 计算前往最终目的地(GSK)的行程数量。

输出

## 
##  GSK Home 
##  105  100	

table() 函数表明有 105 次行程去 GSK,100 次行程回家。

我们可以过滤数据,返回一个包含 105 个观测值的数据集,以及另一个包含 100 个观测值的数据集。

# Select observations
if GoingTo == Home
select_home <- filter(df, GoingTo == "Home")
dim(select_home)

输出

## [1] 100  14
# Select observations
if GoingTo == Work
select_work <- filter(df, GoingTo == "GSK")
dim(select_work)

输出

## [1] 105  14

多个标准

我们可以使用多个标准过滤数据集。例如,您可以提取目的地是“Home”且发生在周三的观测值。

select_home_wed <- filter(df, GoingTo == "Home" & DayOfWeek == "Wednesday")
dim(select_home_wed)

输出

## [1] 23 14

有 23 个观测值符合此标准。

管道

创建数据集需要许多操作,例如

  • 导入
  • 合并
  • 选择
  • 过滤
  • 等等

dplyr 库带有一个实用的运算符 %>%,称为 **管道**。管道功能使操作干净、快速且不易出错。

此运算符是一段代码,它执行步骤而不将中间步骤保存到硬盘。如果我们回到上面的例子,您可以选择感兴趣的变量并过滤它们。我们有三个步骤

  • 步骤 1:导入数据:导入 gps 数据
  • 步骤 2:选择数据:选择 GoingTo 和 DayOfWeek
  • 步骤 3:过滤数据:仅返回 Home 和 Wednesday

我们可以使用传统方式来完成

# Step 1
step_1 <- read.csv(PATH)

# Step 2 
step_2 <- select(step_1, GoingTo, DayOfWeek)

# Step 3 
step_3 <- filter(step_2, GoingTo == "Home", DayOfWeek == "Wednesday")

head(step_3)

输出

##   GoingTo DayOfWeek
## 1    Home Wednesday
## 2    Home Wednesday
## 3    Home Wednesday
## 4    Home Wednesday
## 5    Home Wednesday
## 6    Home Wednesday	

这种方式不适合执行许多操作,尤其是在有很多步骤的情况下。环境会存储大量对象。

让我们改用管道运算符 %>%。我们只需要定义最初使用的数据框,所有过程都会从中流转。

管道的基本语法

New_df <- df %>%
step 1 %>%
step 2 %>%
...
arguments
- New_df: Name of the new data frame 
- df: Data frame used to compute the step
- step: Instruction for each step
- Note: The last instruction does not need the pipe operator `%`, you don't have instructions to pipe anymore
Note: Create a new variable is optional. If not included, the output will be displayed in the console.

您可以按照上面列出的步骤创建第一个管道。

# Create the data frame filter_home_wed.It will be the object return at the end of the pipeline
filter_home_wed <- 

#Step 1
read.csv(PATH) % > % 

#Step 2
select(GoingTo, DayOfWeek) % > % 

#Step 3
filter(GoingTo == "Home",DayOfWeek == "Wednesday")
identical(step_3, filter_home_wed)

输出

## [1] TRUE

我们准备好使用管道运算符创建令人惊叹的数据集了。

arrange()

上一篇教程中,您学习了如何使用 sort() 函数对值进行排序。dplyr 库有自己的排序函数。它与管道配合得天衣无缝。arrange() 动词可以按升序(默认)或降序重新排序一个或多个行。

- `arrange(A)`: Ascending sort of variable A
- `arrange(A, B)`: Ascending sort of variable A and B
- `arrange(desc(A), B)`: Descending sort of variable A and ascending sort of B

我们可以按目的地对距离进行排序。

# Sort by destination and distance
step_2_df <-step_1_df %>%
	arrange(GoingTo, Distance)
head<step_2_df)

输出

##     X       Date StartTime DayOfWeek GoingTo Distance MaxSpeed AvgSpeed
## 1 193  7/25/2011     08:06    Monday     GSK    48.32    121.2     63.4
## 2 196  7/21/2011     07:59  Thursday     GSK    48.35    129.3     81.5
## 3 198  7/20/2011     08:24 Wednesday     GSK    48.50    125.8     75.7
## 4 189  7/27/2011     08:15 Wednesday     GSK    48.82    124.5     70.4
## 5  95 10/11/2011     08:25   Tuesday     GSK    48.94    130.8     85.7
## 6 171  8/10/2011     08:13 Wednesday     GSK    48.98    124.8     72.8
##   AvgMovingSpeed FuelEconomy TotalTime MovingTime Take407All
## 1           78.4        8.45      45.7       37.0         No
## 2           89.0        8.28      35.6       32.6        Yes
## 3           87.3        7.89      38.5       33.3        Yes
## 4           77.8        8.45      41.6       37.6         No
## 5           93.2        7.81      34.3       31.5        Yes
## 6           78.8        8.54      40.4       37.3         No

摘要

下表总结了您在本教程中学到的所有操作。

动词 目标 代码 解释
glimpse 检查 df 的结构
glimpse(df)
与 str() 相同
select() 选择/排除变量
select(df, A, B ,C)
选择变量 A、B 和 C
select(df, A:C)
选择从 A 到 C 的所有变量
select(df, -C)
排除 C
filter() 根据一个或多个条件过滤 df
filter(df, condition1)
一个条件
filter(df, condition1
条件2)
arrange() 按一个或多个变量对数据集进行排序
arrange(A)
变量 A 的升序排序
arrange(A, B)
变量 A 和 B 的升序排序
arrange(desc(A), B)
变量 A 的降序排序和变量 B 的升序排序
%>% 在每个步骤之间创建管道
step 1 %>% step 2 %>% step 3