dplyr简介

dplyr是R语言的数据分析包,类似于python中的pandas,能对dataframe类型的数据做很方便的数据处理和分析操作。

安装并导入dplyr包

install.packages("dplyr")
library(dplyr)

准备测试数据

我们使用dplyr包中内置的starwars数据集作为测试数据

starwars    #查看starwars数据集中的数据
class(starwars)     # 查看数据类型
colnames(starwars)    #查看数据的字段
dim(starwars)     #  查看dataframe的大小

如果你是从外部读入数据或自己构造的数据,那么在dplyr包中内可以首先将的数据整理成更友好的tbl_df数据:

#先查看数据类型
data <- data.frame(person=c('Alex','Bob','Cathy'),grade=c(2,3,4),score=c(78,89,88))
class(data)
#转换为tbl_df类型
ds <- tbl_df(data)
#转换为data.frame类型
df <- as.data.frame(ds)

管道符 %>%

在dplyr中有一个比较有特色的管道符 %>% 有必要先说明一下,其作用是将前一步的结果直接传参给下一步的函数,从而省略了中间的赋值步骤,可以大量减少内存中的对象,节省内存。该符号将左边的对象作为第一个参数传递到右边的函数中.
举个例子来说,在上面查看数据集的字段中我们使用语句colnames(starwars),用管道符%>%来写的话就是starwars %>% colnames()

#管道函数
#默认是传递至后面函数的第一个参数
df %>% head(2)
  a b
1 1 a
2 2 b
#当需要传递至后面函数的非第一个参数时,使用“.”代替
"a_b" %>% str_c("c_", ., sep = "")
[1] "c_a_b"

dplyr常用函数

排列Arrange

arrange()按给定的列名依次对行进行排序,语法为arrange(.data, ...)

arrange(starwars, height)  #升序排列
arrange(starwars, -height)  #降序排列
arrange(starwars, desc(height))  #降序排列,使用desc()函数
starwars %>% arrange(-height)  #管道函数方法:降序排列

选择Select

select()用列名作参数来选择子数据集。dplyr包中提供了些特殊功能的函数与select函数结合使用, 用于筛选变量,包括starts_with,ends_with,contains,matches,one_of,num_range和everything等。语法 为select(.data, ...)

#选取多列
select(starwars, name,height,mass,hair_color)
#选取多列并改变顺序
select(starwars, height,mass,name,hair_color)
#选取列名以s开始的列
select(starwars, starts_with("s"))
#选取列名后缀包含color的列
select(starwars, ends_with("color"))
#选取列名后缀不包含color的列
select(starwars, -ends_with("color"))
#选取列名中包含_的列
select(starwars, contains("_"))
#正则表达式匹配,返回变量名中包含t的列
select(starwars, matches(".t."))
#使用冒号连接列名,选择多个列
select(starwars, name:hair_color)
#选择字符向量中的列,select中不能直接使用字符向量筛选,需要使用one_of函数
vars <- c("name", "hair_color")
select(starwars, one_of(vars))
#返回指定字符向量之外的列
select(starwars, -one_of(vars))
#返回所有列,一般调整数据集中变量顺序时使用,例如把hair_color列放到最前面
select(starwars, hair_color, everything())

select也可以用来重命名:

#重命名列hair_color,返回子数据集只包含重命名的列
select(starwars, haircolor = hair_color)
#重命名所有以color为后缀的列,返回子数据集只包含重命名的列
select(starwars, color = ends_with("color"))
#重命名列hair_color,返回全部列,使用rename函数
rename(starwars,, haircolor = hair_color)

筛选Filter

filter()函数可以按给定的逻辑条件筛选出符合要求的子数据集.同时也可以根据行号筛选数据,语法为语法 filter(.data, ...)

#筛选出height为150的行
filter(starwars, height == 150)
#筛选出sex为female的行
filter(starwars, sex == 'female')
#筛选出skin_color为light并且height等于150的行
filter(starwars, skin_color == 'light' & height == 150)
filter(starwars, skin_color == 'light',height == 150)
#筛选出skin_color为light或者height等于150的行
filter(starwars, skin_color == 'light' | height == 150)
#过滤出height等于150或159的行
filter(starwars, height %in% c(150, 165))

#filter()函数和slice()函数根据行号筛选数据
#选取第一行数据
slice(starwars, 1L)
filter(starwars, row_number() == 1L)
#选取最后一行数据
slice(starwars, n())
filter(starwars, row_number() == n())
#选取第5行到最后一行所有数据
slice(starwars, 5:n())
filter(starwars, between(row_number(), 5, n()))

变形mutate

mutate函数对已有列进行数据运算并添加为新列,同时还有另外一个函数transmute()只返回扩展的新变量。语法为mutate(.data, ...)transmute(.data, ...)

# 添加两列:ht_m将身高数据除以100,color列连接skin_color和eye_color两列
mutate(starwars, ht_m = height/100,color =paste(starwars$skin_color,starwars$eye_color,sep="_"))
#计算新列wt_kg和wt_t,返回对象中只包含新列
transmute(starwars, ht_m = height/100,color =paste(starwars$skin_color,starwars$eye_color,sep="_"))
#添加新列,在同一语句中可以使用刚添加的列,注意这里不用添加dataframe名,否则会报错
mutate(starwars, ht_m = height/100,ht_m_text =paste(ht_m,"m",sep="_"))

抽样sample

抽样函数,sample_n()随机抽取指定数目的样本,sample_frac()随机抽取指定百分比的样本,默认都为不放回抽样,通过设置replacement = TRUE可改为放回抽样,可以用于实现Bootstrap抽样。语法为sample_n(tbl, size, replace = FALSE, weight = NULL, .env = parent.frame())在新版本的dplyr包中抽样函数已变为slice_sample。

#无放回抽样10行数据
sample_n(starwars, 10)
#有放回抽样20行数据
sample_n(starwars, 20, replace = TRUE)
#默认size=1,相当于对全部数据无放回抽样
sample_frac(starwars)
#无放回抽样10%的数据
sample_frac(starwars, 0.1)

# 按个数抽样
slice_sample(starwars,n = 10)
# 按比例抽样
slice_sample(starwars,prop = 0.1)

汇总summarise

对数据框调用其它函数进行汇总操作, 返回一维的结果,返回多维结果时会报如下错误:Error: expecting result of length one, got : 2,语法为summarise(.data, ...)
注意在使用统计函数时保证数据不存在缺失值,否则结果会返回NA,可以利用na.omit(starwars)来去抽除数据框中包含NA的行.

#返回数据中height的均值
summarise(na.omit(starwars), mean(height))
#返回数据中height的标准差
summarise(na.omit(starwars), sd(height))
#返回数据中height的最大值及最小值
summarise(na.omit(starwars), max(height), min(height))
#返回数据框的行数
summarise(starwars, n())
#返回sex去重后的个数数
summarise(starwars, n_distinct(sex))
#返回height的第一个值
summarise(starwars, first(height))
#返回height的最后一个值
summarise(starwars, last(height))

分组group_by

group_by()函数用于对数据集按照给定变量分组,返回分组后的数据集。对返回后的数据集使用以上介绍的函数时,会自动的对分组数据操作。

#使用变量sex对starwars分组,返回分组后数据集,注意去除数据集中的NA
sw_group <- group_by(na.omit(starwars), sex)
#返回每个分组中最大height所在的行
filter(sw_group, height == max(height))
#返回每个分组中变量名包含d的列,同时始终返回列sex(上述分组依据列)
select(sw_group, contains("d"))
#使用height对每个分组排序
arrange(sw_group,  height)
#对每个分组无放回抽取2行
sample_n(sw_group, 2)
#求每个分组中height和birth_year的均值
summarise(sw_group, mean(height), mean(birth_year))
#返回每个分组中height第二的值
summarise(sw_group, nth(height,2))


#获取分组数据集所使用的分组变量
groups(sw_group)
#ungroup从数据框中移除组合信息,因此返回的分组变量为NULL
groups(ungroup(sw_group))

数据连接join

数据框中经常需要将多个表进行连接操作, 如左连接、右连接、内连接等,dplyr包也提供了数据集的连接操作,类似于 base::merge() 函数。语法如下:

  #内连接,合并数据仅保留匹配的记录
  inner_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...) 

  #左连接,向数据集x中加入匹配的数据集y记录
  left_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)

  #右连接,向数据集y中加入匹配的数据集x记录
  right_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...) 

  #全连接,合并数据保留所有记录,所有行
  full_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)

  #返回能够与y表匹配的x表所有记录 
  semi_join(x,y, by = NULL, copy = FALSE, ...)

  #返回无法与y表匹配的x表的所有记录
  anti_join(x, y, by = NULL, copy = FALSE, ...)

by设置两个数据集用于匹配的字段名,默认使用全部同名字段进行匹配,如果两个数据集需要匹配的字段名不同,可以直接用等号指定匹配的字段名,如, by = c(“a” = “b”),表示用x.a和y.b进行匹配。如果两个数据集来自不同的数据源,copy设置为TRUE时,会把数据集y的数据复制到数据集x中,出于性能上的考虑,需要谨慎设置copy参数为TRUE。合并后的数据集中同名变量,会自动添加suffix中设置的后缀加以区分。

df1 = data.frame(CustomerId=c(1:6), sex = c("f", "m", "f", "f", "m", "m"), Product=c(rep("Toaster",3), rep("Radio",3)))
df2 = data.frame(CustomerId=c(2,4,6,7),sex = c( "m", "f", "m", "f"), State=c(rep("Alabama",3), rep("Ohio",1)))
#内连接,默认使用"CustomerId"和"sex"连接
inner_join(df1, df2)
#左连接,默认使用"CustomerId"和"sex"连接
left_join(df1, df2)
#右连接,默认使用"CustomerId"和"sex"连接
right_join(df1, df2)
#全连接,默认使用"CustomerId"和"sex"连接
full_join(df1, df2)
#内连接,使用"CustomerId"连接,同名字段sex会自动添加后缀
inner_join(df1, df2, by = c("CustomerId" = "CustomerId"))
#以CustomerId连接,返回df1中与df2匹配的记录
semi_join(df1, df2, by = c("CustomerId" = "CustomerId"))
#以CustomerId和sex连接,返回df1中与df2不匹配的记录
anti_join(df1, df2)

dplyr包在R语言中也经常和tidyr包一起使用进行数据清洗,tidyr包的使用可以查看:http://smilecoc.vip/2021/09/03/R_tidyr/

参考链接:
https://blog.csdn.net/wltom1985/article/details/54973811
https://zhuanlan.zhihu.com/p/150457098
https://www.cnblogs.com/shangfr/p/6110614.html