原创
R
数据分析
dplyr
是 R 中最为实用的package之一,是data manipulation的一大利器。功能上,dplyr
支持过滤(filter)、切片(slice)、排列(arrange)、变换(mutate)、分组(group)、概括(summarise)等一系列常见的表格操作;结构上,dplyr
的函数的参数设计充分兼容pipe操作符,使得用户可以写出比使用内置data.frame格式以及关联方法更为优雅、可读性更高的代码。
练习数据:dplyr
包自带的starwars
library(dplyr)
sw <- starwars
数据预览:
tibble默认展示前十行
数据简介:
原始数据来自swapi,该网址现已停止服务
数据共87行13列,列变量为:
- name: 角色名
- height: 身高(cm)
- mass: 体重(kg)
- hair_color,skin_color,eye_color: 发色、肤色及瞳色
- birth_year: 出生年月(BBY=雅汶战役前)
- gender: 雄性、雌性、雌雄同体或无性
- homeworld: 故乡
- species: 种族
- films: 出场的电影列表
- vehicles: 角色驾驶过的车辆
- starships: 角色驾驶过的飞船
常用操作
筛选(filter)
# 选出星球大战数据集中的所有种族为人类的角色
humans <- filter(sw,species=="Human")
# 多重条件
# 选出所有黑发的人族角色
humanwithblackhair <- sw %>% filter(species=="Human",hair_color=="black")
# 等价于
humanwithblackhair <- humans %>% filter(hair_color=="black")
humans
humanwithblackhair
在功能上等价于同名data.frame的conditional indexing
# 此处sw为同名data.frame
humanwithblackhair <- sw[sw$species=="Human"&sw$hair_color=="black",]
切片(slice)
# 偶数列
evenrows <- slice(sw,seq(1,dim(sw)[1],2))
evenrows
与filter
的区别在于用的是直接用行序号(position)
排列(arrange)
# 按照身高逆序排列
rankbyheight <- arrange(sw,desc(height))
等价于data.frame+order
rankbyheight <- sw[order(sw$height,decreasing=TRUE),]
rankbyheight
# bootstrap sampling
bootstrapping2X <- slice_sample(sw,prop=2,replace=TRUE)
选择(select)
# 选出所有颜色属性相关的列
# 方法一:罗列
attribute.color <- select(sw,hair_color,skin_color,eye_color)
# 方法二:切片
attribute.color <- select(sw,hair_color:eye_color)
# 方法三:匹配
attribute.color <- select(sw,ends_with("color")) # 在这里可以与contains互换
attribute.color
变幻(mutate)和转换(transmute)
# 为角色计算BMI指数(新增身高和BMI列)
sw_addBMI <- sw %>% mutate(height_m=height/100,BMI=mass/height_m^2,.before=hair_color)
# 只取计算所得的BMI
BMI <- sw %>% transmute(height_m=height/100,BMI=mass/height_m^2,.before=hair_color)
sw_addBMI
BMI
分组(group)和概括(summarise)
# 为每个种族计算平均身高
avgheightbyspecies <- sw %>% group_by(species) %>%
select(species,height) %>%
summarise(avg.height=mean(height,na.rm=TRUE))
avgheightbyspecies
参考链接:
dplyr官方overview