以示例数据库iris学习dplyr包
安装与设置镜像
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
install.packages("dplyr")
library(dplyr)
dplyr的基础函数
1.新增列:mutate
使用示例
mutate(test, new = Sepal.Length * Sepal.Width)
2.按列筛选:select
3.按行筛选:filter
使用示例
filter(test, Species == "setosa")
4.按某1列或某几列对整个表格进行排序:arrange
使用示例
arrange(test, Sepal.Length)#默认从小到大排序
5.汇总:summarise
summarise(test, mean(Sepal.Length), sd(Sepal.Length))
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
R结果
实用技能
1.管道符号:%>% (传递作用)
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
2.统计某列unique的值:count
count(test,Species)
test
处理关系数据,将两个表进行连接
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,5,6),
stringsAsFactors = F)
1.取交集:inner_join(,,by=)
2.左侧连接:left_join(,, by=) ,不是取交集
left_join(test1, test2, by = 'x')
## x z y
## 1 b A 2
## 2 e B 5
## 3 f C 6
## 4 x D NA
left_join(test2, test1, by = 'x')
## x y z
## 1 a 1
## 2 b 2 A
## 3 c 3
## 4 d 4
## 5 e 5 B
## 6 f 6 C
3、全连接:full_join(,,by = )
4、半连接:semi_join 返回能够与y表匹配的x表的所有记录
semi_join(x= test1, y=test2,by='x')
semi_join(x = test1, y = test2, by = 'x')
## x z
## 1 b A
## 2 e B
## 3 f C
5、反连接:anti_join 返回无法与y表匹配的x表的所有记录
anti_join(x = test2, y = test1, by = 'x')
## x y
## 1 a 1
## 2 c 3
## 3 d 4
6、合并
相当于base包里的cbind()函数和rbind()函数;注意,bind_rows()函数需要两个表格列数相同,而bind_cols()函数则需要两个数据框有相同的行数