学习R包
- 安装R包
install.packages("dplyr")
library(dplyr) require(dplyr) 加载R包
- 五个基础函数的学习
使用R内置iris数据集
test <- iris[c(1:2,51:51,101:102)]
-新增列
mutate()
mutate(test, new = Sepal.Length*Sepal.Width)
- 按列筛选
select(test,1)
select(test,c(1,5) 选择第一列和第五列
select(test,Sepal.Length) 选择Sepal.Length这一列
select(test, Petal.Length,Petal.Width)
vars <- c("Petal.Length","Petal.Width")
select(test,one_of(vars)
- 筛选行
filter(test, Species == "setosa")
filter(test, Species == "setosa"&Sepal.Length > 5) 选择种族是setosa并且Sepal.Length大于5的
filter(test, Species %in% c("setosa","versicolor")) 选择种族和setosa,versicolor重合的
- 对表格进行排序
arrange(test, Sepal.Length) 根据Sepal.Length对表格进行排序 #默认从小到大排列
arrange(test,desc(Sepal.Length) 从大到小排列
- 对数据进行汇总
summarise(test,mean(Sepal.Length), sd(Sepal.Length)) 计算Sepal.Length的平均值和标准差
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length)) 按照Species分组后,计算每组的平均值和标准差
- dplyr的两个使用技能
- 管道操作 %>%
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length),sd(Sepal.Length))
- count 统计某一列的unique值
count(test,Species)
- dplyr 处理关系数据
两个表进行连接
options(stringsAsFactors = F)
test1 <- data.frame(x = c('b','e','f','x'),
(z = c("A","B","C","D"),
stringsAsFactors = F)
test2 <- data.frame(x = c('a','b','c','d','e','f'),
(y = c(1,2,3,4,,6),
stringsAsFactors = F)
inner_join(test1,test2,by = "x") 取两个表格中的交集
left_join(test1,test2, by = 'x') 选择左表中的全部行
left_join(test2,test1, by = 'x') 可以比较区别
full_join(test1,test2, by = 'x') 包含两个表格中的全部行
semi_join(x= test1, y=test2, by = 'x') 能够与y表匹配的x表的所有记录
anti_join(x= test2, y = test1, by = 'x') 无法与y表匹配的x表的所有记录
- 合并
bind_rows(test1,test2) 两个表格列数相同
bind_cols(test1,test2) 两个表格行数相同