Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >R语言包_dplyr_1

R语言包_dplyr_1

作者头像
用户1147754
发布于 2019-05-26 13:40:52
发布于 2019-05-26 13:40:52
1K00
代码可运行
举报
文章被收录于专栏:YoungGyYoungGy
运行总次数:0
代码可运行

有5个基础的函数: - filter - select - arrange - mutate - summarise - group_by (plus)

可以和databases以及data tables中的数据打交道。

plyr包的特点

其基础函数有以下特点:

  1. 第一个参数df
  2. 返回df
  3. 没有数据更改in place

正是因为有这些特点,才可以使用%>%操作符,方便逻辑式编程。

载入数据

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
library(plyr)
library(dplyr)

# load packages
suppressMessages(library(dplyr))
install.packages("hflights")
library(hflights)
# explore data
data(hflights)
head(hflights)
# convert to local data frame
flights <- tbl_df(hflights)
# printing only shows 10 rows and as many columns as can fit on your screen
flights
# you can specify that you want to see more rows
print(flights, n=20)
# convert to a normal data frame to see all of the columns
data.frame(head(flights))

filter

keep rows matching criteria

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# base R approach to view all flights on January 1
flights[flights$Month==1 & flights$DayofMonth==1, ]
# dplyr approach
# note: you can use comma or ampersand to represent AND condition
filter(flights, Month==1, DayofMonth==1)
# use pipe for OR condition
filter(flights, UniqueCarrier=="AA" | UniqueCarrier=="UA")
# you can also use %in% operator
filter(flights, UniqueCarrier %in% c("AA", "UA"))

select

pick columns by name

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# base R approach to select DepTime, ArrTime, and FlightNum columns
flights[, c("DepTime", "ArrTime", "FlightNum")]
# dplyr approach
select(flights, DepTime, ArrTime, FlightNum)
# use colon to select multiple contiguous columns, and use `contains` to match columns by name
# note: `starts_with`, `ends_with`, and `matches` (for regular expressions) can also be used to match columns by name
select(flights, Year:DayofMonth, contains("Taxi"), contains("Delay"))

“chaining” or “pipelining”

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# nesting method to select UniqueCarrier and DepDelay columns and filter for delays over 60 minutes
filter(select(flights, UniqueCarrier, DepDelay), DepDelay > 60)
# chaining method
flights %>%
    select(UniqueCarrier, DepDelay) %>%
    filter(DepDelay > 60)

# create two vectors and calculate Euclidian distance between them
x1 <- 1:5; x2 <- 2:6
sqrt(sum((x1-x2)^2))
# chaining method
(x1-x2)^2 %>% sum() %>% sqrt()

arrange

reorder rows

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# base R approach to select UniqueCarrier and DepDelay columns and sort by DepDelay
flights[order(flights$DepDelay), c("UniqueCarrier", "DepDelay")]
# dplyr approach
flights %>%
    select(UniqueCarrier, DepDelay) %>%
    arrange(DepDelay)
# use `desc` for descending
flights %>%
    select(UniqueCarrier, DepDelay) %>%
    arrange(desc(DepDelay))

mutate

add new variable create new variables that are functions of exciting variables which is d ifferent form transform

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# base R approach to create a new variable Speed (in mph)
flights$Speed <- flights$Distance / flights$AirTime*60
flights[, c("Distance", "AirTime", "Speed")]
# dplyr approach (prints the new variable but does not store it)
flights %>%
    select(Distance, AirTime) %>%
    mutate(Speed = Distance/AirTime*60)
# store the new variable
flights <- flights %>% mutate(Speed = Distance/AirTime*60)

summarise

reduce variables to values

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# base R approaches to calculate the average arrival delay to each destination
head(with(flights, tapply(ArrDelay, Dest, mean, na.rm=TRUE)))
head(aggregate(ArrDelay ~ Dest, flights, mean))
# dplyr approach: create a table grouped by Dest, and then summarise each group by taking the mean of ArrDelay
flights %>%
    group_by(Dest) %>%
    summarise(avg_delay = mean(ArrDelay, na.rm=TRUE))
#summarise_each allows you to apply the same summary function to multiple columns at once
#Note: mutate_each is also available
# for each carrier, calculate the percentage of flights cancelled or diverted
flights %>%
    group_by(UniqueCarrier) %>%
    summarise_each(funs(mean), Cancelled, Diverted)
# for each carrier, calculate the minimum and maximum arrival and departure delays
flights %>%
    group_by(UniqueCarrier) %>%
    summarise_each(funs(min(., na.rm=TRUE), max(., na.rm=TRUE)), matches("Delay"))
#Helper function n() counts the number of rows in a group
#Helper function n_distinct(vector) counts the number of unique items in that vector
# for each day of the year, count the total number of flights and sort in descending order
flights %>%
    group_by(Month, DayofMonth) %>%
    summarise(flight_count = n()) %>%
    arrange(desc(flight_count))
# rewrite more simply with the `tally` function
flights %>%
    group_by(Month, DayofMonth) %>%
    tally(sort = TRUE)
# for each destination, count the total number of flights and the number of distinct planes that flew there
flights %>%
    group_by(Dest) %>%
    summarise(flight_count = n(), plane_count = n_distinct(TailNum))
# Grouping can sometimes be useful without summarising
# for each destination, show the number of cancelled and not cancelled flights
flights %>%
    group_by(Dest) %>%
    select(Cancelled) %>%
    table() %>%
    head()

Window Functions

  • Aggregation function (like mean) takes n inputs and returns 1 value
  • Window function takes n inputs and returns n values Includes ranking and ordering functions (like min_rank), offset functions (lead and lag), and cumulative aggregates (like cummean).
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# for each carrier, calculate which two days of the year they had their longest departure delays
# note: smallest (not largest) value is ranked as 1, so you have to use `desc` to rank by largest value
flights %>%
    group_by(UniqueCarrier) %>%
    select(Month, DayofMonth, DepDelay) %>%
    filter(min_rank(desc(DepDelay)) <= 2) %>%
    arrange(UniqueCarrier, desc(DepDelay))
# rewrite more simply with the `top_n` function
flights %>%
    group_by(UniqueCarrier) %>%
    select(Month, DayofMonth, DepDelay) %>%
    top_n(2,DepDelay) %>%
    arrange(UniqueCarrier, desc(DepDelay))

# for each month, calculate the number of flights and the change from the previous month
flights %>%
    group_by(Month) %>%
    summarise(flight_count = n()) %>%
    mutate(change = flight_count - lag(flight_count))

# rewrite more simply with the `tally` function
flights %>%
    group_by(Month) %>%
    tally() %>%
    mutate(change = n - lag(n))

Other functions

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# randomly sample a fixed number of rows, without replacement
flights %>% sample_n(5)

# randomly sample a fraction of rows, with replacement
flights %>% sample_frac(0.25, replace=TRUE)

# base R approach to view the structure of an object
str(flights)

# dplyr approach: better formatting, and adapts to your screen width
glimpse(flights)

Connecting Databases

  • dplyr can connect to a database as if the data was loaded into a data frame
  • Use the same syntax for local data frames and databases
  • Only generates SELECT statements
  • Currently supports SQLite, PostgreSQL/Redshift, MySQL/MariaDB, BigQuery, MonetDB
  • Example below is based upon an SQLite database containing the hflights data
  • Instructions for creating this database are in the databases vignette
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# connect to an SQLite database containing the hflights data
my_db <- src_sqlite("my_db.sqlite3")

# connect to the "hflights" table in that database
flights_tbl <- tbl(my_db, "hflights")

# example query with our data frame
flights %>%
    select(UniqueCarrier, DepDelay) %>%
    arrange(desc(DepDelay))

# identical query using the database
flights_tbl %>%
    select(UniqueCarrier, DepDelay) %>%
    arrange(desc(DepDelay))

You can write the SQL commands yourself dplyr can tell you the SQL it plans to run and the query execution plan

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# send SQL commands to the database
tbl(my_db, sql("SELECT * FROM hflights LIMIT 100"))

# ask dplyr for the SQL commands
flights_tbl %>%
    select(UniqueCarrier, DepDelay) %>%
    arrange(desc(DepDelay)) %>%
    explain()

参考资料

  1. justmarkham的教程1
  2. justmarkdown的教程2
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年09月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
R语言包_dplyr_2
data_frame() is a better way than data.frame() for creating data frames. Benefits of data_frame():
用户1147754
2019/05/26
7380
R数据科学|3.6习题解答
这个问题是数据分析的一个基本问题:成本函数。作为分析人员,我们之所以对航班延误感兴趣,是因为对乘客来说代价高昂。在许多情况下,到达延迟更重要。在大多数情况下,迟到对乘客来说成本更高,因为这可能会打乱其下一阶段的旅行,例如转机或预定的会议。如果出发在不影响到达时间的情况下延迟,则此延迟不会影响计划,也不会影响旅行总时间。如果在飞机上狭窄的范围内花费更少的时间,如果这种延迟时间仍然花在跑道上的狭窄范围内,那么这种延迟可能是有益的。
庄闪闪
2021/04/09
3.9K0
R数据科学|3.7内容介绍及习题解答
虽然与summarize()函数结合起来使用是最有效的,但分组也可以与mutate()和filter()函数结合,以完成非常便捷的操作。示例如下:
庄闪闪
2021/04/09
4.2K0
ClickHouse入门实例-样例数据(ontime)
参考官方文档https://clickhouse.tech/docs/en/getting-started/example-datasets/ontime/
程裕强
2020/09/17
1.1K0
ClickHouse入门实例-样例数据(ontime)
dpois函数_frequency函数
https://r4ds.had.co.nz/transform.html#grouped-summaries-with-summarise
全栈程序员站长
2022/09/20
1.9K0
dpois函数_frequency函数
使用dplyr进行数据转换
dplyr最常用的5个函数: • 按值筛选观测(filter())。 • 对行进行重新排序(arrange())。 • 按名称选取变量(select())。 • 使用现有变量的函数创建新变量(mutate())。 • 将多个值总结为一个摘要统计量(summarize())。 函数的使用方法: (1) 第一个参数是一个数据框。 (2) 随后的参数使用变量名称(不带引号)描述了在数据框上进行的操作。 (3) 输出结果是一个新数据框。
生信编程日常
2020/04/01
1.1K0
R语言数据处理:飞机航行距离与到达延误时间有什么关系??
数据分析有一半以上的时间会花在对原始数据的整理及变换上,包括选取特定的分析变量、汇总并筛选满足条件的数据、排序、加工处理原始变量并生成新的变量、以及分组汇总数据等等。这一点,我想大部分使用EXCEL的童鞋都深有体会,写论文时,这么多的数据进行处理,手动汇总、筛选、变换,工作量实在是太大。而本文介绍的dplyr包简直就是Hadley Wickham (ggplot2包的作者,被称作“一个改变R的人”)大神为我们提供的“数据再加工”神器啊。 本文试图通过一个案例,对神奇的dplyr包的一些常用功能做简要介绍
机器学习AI算法工程
2018/03/14
3.3K0
R语言数据处理:飞机航行距离与到达延误时间有什么关系??
R数据科学|5.5.2内容介绍及课后习题解答
要想对两个分类变量间的相关变动进行可视化表示,需要计算出每个变量组合中的观测数量。常用的两种方法有:
庄闪闪
2021/04/09
1.9K0
「R」数据操作(七):dplyr 操作变量与汇总
除了选择已存在的列,另一个常见的操作是添加新的列。这就是mutate()函数的工作了。
王诗翔呀
2020/07/06
2.7K0
「R」数据操作(七):dplyr 操作变量与汇总
Day5 r包使用
用户11074272
2024/04/19
1350
R数据科学|3.5内容介绍及习题解答
上节我们对选择现有的列进行了介绍与习题解答,现在对数据框添加新列进行介绍,这里使用mutate()函数,注意:mutate()总是将新列添加在数据集的最后。
庄闪闪
2021/04/09
2.7K3
数据清洗与管理之dplyr、tidyr
先前已经讲过R语言生成测试数据、数据预处理和外部数据输入等内容,但这仅仅是第一步,我们还需要对数据集进行筛选、缺失值处理等操作,以便获得可以应用于建模或者可视化的数据集(变量)。接下来就以鸢尾花测试数据集进行进一步的数据管理和筛选操作。
1480
2019/06/20
1.9K0
数据清洗与管理之dplyr、tidyr
Day6:学习R包
用户10859122
2023/12/03
1930
R语言之 dplyr 包
这个包以一种统一的规范更高效地处理数据框。dplyr 包里处理数据框的所有函数的第一个参数都是数据框名。
timerring
2023/10/13
5550
R语言之 dplyr 包
R语言安装R包DAY6-Gaozsi
一个新数据框,其中包含键、 x 值和 y 值。我们使用 by 参数告诉 dplyr 哪个变量是键:
gaozsi
2024/02/25
1890
从头学R语言——DAY 3
R包直接在Rstudio页面下载的3大来源:官网CRAN、Biocductor、github
橙子7
2024/07/25
1500
常用R包-dplyr
dplyr是一个在R语言中非常流行的数据处理包,它提供了许多功能强大且易于使用的函数,包括 select、 filter、mutate、arrange和summarize 等。这些功能使得dplyr成为数据清洗、处理和分析的首选包。
用户11076492
2024/04/18
5200
「R」数据操作(六):dplyr 排序和选择
arrange()函数工作原理和filter()相似,但它不是选择行,而是改变行的顺序。它使用一个数据框和一系列有序的列变量(或者更复杂的表达式)作为输入。如果你提供了超过一个列名,其他列对应着进行排序。
王诗翔呀
2020/07/06
4.2K0
如何在 CDP 的湖仓一体中使用Iceberg
2022 年 6 月,Cloudera宣布在 Cloudera 数据平台 (CDP) 中全面推出 Apache Iceberg。Iceberg 是一种 100% 开放表格式,由Apache Software Foundation开发,可帮助用户避免供应商锁定并实现开放式 Lakehouse。
大数据杂货铺
2022/12/02
1.5K0
如何在 CDP 的湖仓一体中使用Iceberg
「R」dplyr 列式计算
同时对数据框的多列执行相同的函数操作经常有用,但是通过拷贝和粘贴的方式进行的话既枯燥就容易产生错误。
王诗翔呀
2022/01/21
2.6K0
相关推荐
R语言包_dplyr_2
更多 >
LV.1
这个人很懒,什么都没有留下~
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验