安装和加载R包
dplyr包为例
- 镜像设置
程序设置
代码 - 安装
install.packages(“包”)
BiocManager::install(“包”)
- 加载
library(包)
require(包)
- 代码运行
安装R包####
install.packages("dplyr")
library(dplyr)
test <- iris[c(1:2,51:52,101:102),]dplyr五个基础函数####
1.mutate(),新增列####
?mutate()
mutate(test,new = Sepal.Length*Sepal.Width)
test <- mutate(test,new = testSepal.Width)2.select(),按列筛选####
按列号筛选
select(test,1)
select(test,c(1,5))
select(test,Sepal.Length)按行名筛选
select(test, Petal.Length, Petal.Width)
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))3.filter()筛选行####
filter(test,Species=="setosa")
filter(test,Species=="setosa"&Sepal.Length>5)
filter (test,Species%in%c("setosa","versicolor"))4.arrange(),按照某1列和某几列排序####
arrange(test,testSepal.Length))
5.summarise():汇总
summarise(test,mean(testSepal.Length))#计算均值和方
new_test <- group_by(test,testSpecies),mean(Sepal.Length), sd(Sepal.Length))dplyr两个实用技能####
1.管道操作%>% #加载任意一个tidyverse(ctr + shift + M)
new_test %>% group_by(Species) %>% summarise(mean(Sepal.Length), sd(Sepal.Length))
2.count 统计某列的uinque值
count(test,Species)
dplyr处理关系####
rm(list = ls())
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(test1, test2, by = "x")
2.左连
left_join(test1, test2, by = 'x')
left_join(test2, test1, by = 'x')3.全连
full_join( test1, test2, by = 'x')
4.半连接:返回能够与y表匹配的x表所有记录
semi_join(x = test1, y = test2, by = 'x')
semi_join(x=test2,y=test1,by="x")5.反连接:返回无法与y表匹配的x表的所记录
anti_join(x = test2, y = test1, by = 'x')
6.简单合并
在相当于base包里的cbind()函数和rbind()函数;注意,bind_rows()函数需要两个表格列数相同,而>bind_cols()函数则需要两个数据框有相同的行数
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
test2 <- data.frame(x = c(5,6), y = c(50,60))
test3 <- data.frame(z = c(100,200,300,400))
bind_rows(test1, test2)