查看原文
其他

R语言dplyr包实操

大邓 大邓和他的Python 2022-07-09

1. dplyr简介

dplyr是R语言的数据分析包,类似于python中的pandas,能对dataframe类型的数据做很方便的数据处理和分析操作。最初我也很奇怪dplyr这个奇怪的名字,我查到其中一种解释 - d代表dataframe - plyr是英文钳子plier的谐音

dplyr如同R的大多数包,都是函数式编程,这点跟Python面向对象编程区别很大。优点是初学者比较容易接受这种函数式思维,有点类似于流水线,每个函数就是一个车间,多个车间共同完成一个生产(数据分析)任务。

而在dplyr中,就有一个管道符 %>% ,符号左侧表示数据的输入,右侧表示下游数据处理环节。


2. 安装并导入dplyr库

pacman库的p_load函数功能包含了

  1. install.packages(“dplyr”)
  2. library(dplyr)

该写法更简单易用

pacman::p_load("dplyr")

3. 读取数据

#设置工作目录
setwd("/Users/thunderhit/Desktop/dplyr_learn")

#导入csv数据
aapl <- read.csv('aapl.csv'
                 header=TRUE,
                 sep=',',
                 stringsAsFactors = FALSE) %>% as_tibble()
head(aapl)
A tibble: 6 × 6
DateOpenHighLowCloseVolume
<chr><dbl><dbl><dbl><dbl><int>
7-Jul-17142.90144.75142.90144.1819201712
6-Jul-17143.02143.50142.41142.7324128782
5-Jul-17143.69144.79142.72144.0921569557
3-Jul-17144.88145.30143.10143.5014277848
30-Jun-17144.45144.96143.78144.0223024107
29-Jun-17144.71145.13142.28143.6831499368

查看数据类型

class(aapl)
  1. 'tbl_df'

  2. 'tbl'

  3. 'data.frame'

查看数据的字段

colnames(aapl)
  1. 'Date'

  2. 'Open'

  3. 'High'

  4. 'Low'

  5. 'Close'

  6. 'Volume'

查看记录数、字段数

dim(aapl)
  1. 251

  2. 6


4. dplyr常用函数

4.1 Arrange

对appl数据按照字段Volume进行降序排序

arrange(aapl, -Volume)
A tibble: 6 × 6
DateOpenHighLowCloseVolume
<chr><dbl><dbl><dbl><dbl><int>
14-Sep-16108.73113.03108.60111.77112340318
1-Feb-17127.03130.49127.01128.75111985040
27-Jul-16104.26104.35102.75102.9592344820
15-Sep-16113.86115.73113.49115.5790613177
16-Sep-16115.12116.13114.04114.9279886911
12-Jun-17145.74146.09142.51145.4272307330

我们也可以用管道符 %>% ,两种写法得到的运行结果是一致的,可能用久了会觉得管道符 %>% 可读性更强,后面我们都会用 %>% 来写代码。

aapl %>% arrange(-Volume)
A tibble: 6 × 6
DateOpenHighLowCloseVolume
<chr><dbl><dbl><dbl><dbl><int>
14-Sep-16108.73113.03108.60111.77112340318
1-Feb-17127.03130.49127.01128.75111985040
27-Jul-16104.26104.35102.75102.9592344820
15-Sep-16113.86115.73113.49115.5790613177
16-Sep-16115.12116.13114.04114.9279886911
12-Jun-17145.74146.09142.51145.4272307330

4.2 Select

选取 Date、Close和Volume三列

aapl %>% select(Date, Close, Volume)
A tibble: 6 × 3
DateCloseVolume
<chr><dbl><int>
7-Jul-17144.1819201712
6-Jul-17142.7324128782
5-Jul-17144.0921569557
3-Jul-17143.5014277848
30-Jun-17144.0223024107
29-Jun-17143.6831499368

只选取Date、Close和Volume三列,其实另外一种表达方式是“排除Open、High、Low,选择剩下的字段的数据”。

aapl %>% select(-c("Open""High""Low")) 
A tibble: 6 × 3
DateCloseVolume
<chr><dbl><int>
7-Jul-17144.1819201712
6-Jul-17142.7324128782
5-Jul-17144.0921569557
3-Jul-17143.5014277848
30-Jun-17144.0223024107
29-Jun-17143.6831499368

4.3 Filter

按照筛选条件选择数据

#从数据中选择appl股价大于150美元的交易数据
aapl %>% filter(Close>=150
A tibble: 6 × 6
DateOpenHighLowCloseVolume
<chr><dbl><dbl><dbl><dbl><int>
8-Jun-17155.25155.54154.40154.9921250798
7-Jun-17155.02155.98154.48155.3721069647
6-Jun-17153.90155.81153.78154.4526624926
5-Jun-17154.34154.45153.46153.9325331662
2-Jun-17153.58155.45152.89155.4527770715
1-Jun-17153.17153.33152.22153.1816404088

从数据中选择appl - 股价大于150美元 且 收盘价大于开盘价 的交易数据

aapl %>% filter((Close>=150) & (Close>Open))
A tibble: 11 × 6
DateOpenHighLowCloseVolume
<chr><dbl><dbl><dbl><dbl><int>
7-Jun-17155.02155.98154.48155.3721069647
6-Jun-17153.90155.81153.78154.4526624926
2-Jun-17153.58155.45152.89155.4527770715
1-Jun-17153.17153.33152.22153.1816404088
30-May-17153.42154.43153.33153.6720126851
25-May-17153.73154.35153.03153.8719235598
18-May-17151.27153.34151.13152.5433568215
12-May-17154.70156.42154.67156.1032527017
11-May-17152.45154.07152.31153.9527255058
9-May-17153.87154.88153.45153.9939130363
8-May-17149.03153.70149.03153.0148752413

4.4 Mutate

将现有的字段经过计算后生成新字段。

#将最好价High减去最低价Low的结果定义为maxDif,并取log
aapl %>% mutate(maxDif = High-Low,
                log_maxDif=log(maxDif)) 
A tibble: 6 × 8
DateOpenHighLowCloseVolumemaxDiflog_maxDif
<chr><dbl><dbl><dbl><dbl><int><dbl><dbl>
7-Jul-17142.90144.75142.90144.18192017121.850.6151856
6-Jul-17143.02143.50142.41142.73241287821.090.0861777
5-Jul-17143.69144.79142.72144.09215695572.070.7275486
3-Jul-17144.88145.30143.10143.50142778482.200.7884574
30-Jun-17144.45144.96143.78144.02230241071.180.1655144
29-Jun-17144.71145.13142.28143.68314993682.851.0473190

得到记录的位置(行数)

aapl  %>% mutate(n=row_number())  
A tibble: 6 × 7
DateOpenHighLowCloseVolumen
<chr><dbl><dbl><dbl><dbl><int><int>
7-Jul-17142.90144.75142.90144.18192017121
6-Jul-17143.02143.50142.41142.73241287822
5-Jul-17143.69144.79142.72144.09215695573
3-Jul-17144.88145.30143.10143.50142778484
30-Jun-17144.45144.96143.78144.02230241075
29-Jun-17144.71145.13142.28143.68314993686

4.5 Group_By

对资料进行分组,这里导入新的 数据集 weather

#导入csv数据
weather <- read.csv('weather.csv'
                    header=TRUE,
                    sep=',',
                    stringsAsFactors = FALSE) %>% as_tibble()  
weather 
A tibble: 6 × 5
Datecitytemperaturewindspeedevent
<chr><chr><int><int><chr>
1/1/2017new york326Rain
1/1/2017mumbai905Sunny
1/1/2017paris4520Sunny
1/2/2017new york367Sunny
1/2/2017mumbai8512Fog
1/2/2017paris5013Cloudy

按照城市分组

weather %>% group_by(city) 
A grouped_df: 6 × 5
Datecitytemperaturewindspeedevent
<chr><chr><int><int><chr>
1/1/2017new york326Rain
1/1/2017mumbai905Sunny
1/1/2017paris4520Sunny
1/2/2017new york367Sunny
1/2/2017mumbai8512Fog
1/2/2017paris5013Cloudy

为了让大家看到分组的功效,咱们按照城市分别计算平均温度

weather %>% group_by(city) %>% summarise(mean_temperature = mean(temperature))
`summarise()` ungrouping output (override with `.groups` argument)
A tibble: 3 × 2
citymean_temperature
<chr><dbl>
mumbai87.5
new york34.0
paris47.5
weather %>%  summarise(mean_temperature = mean(temperature))
A tibble: 1 × 1
mean_temperature
<dbl>
56.33333

往期文章

小案例: Pandas的apply方法
Python语法快速入门
Python网络爬虫与文本数据分析
读完本文你就了解什么是文本分析
综述:文本分析在市场营销研究中的应用
从记者的Twitter关注看他们稿件的党派倾向?
Pandas时间序列数据操作
70G上市公司定期报告数据集
文本数据清洗之正则表达式
shreport库: 批量下载上海证券交易所上市公司年报
Numpy和Pandas性能改善的方法和技巧
漂亮~pandas可以无缝衔接Bokeh
YelpDaset: 酒店管理类数据集10+G
半个小时学会Markdown标记语法

后台回复关键词【dplyr实操】,可获得测试数据及代码


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存