加载和安装R包
1.镜像设置
file.edit('~/.Rprofile')
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
2.检查
options()$repos
options()$BioC_mirror
3.安装+加载
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是安装包的名字
test <- iris[c(1:2,51:52,101:102),]
dplyr五个基础函数
1.新增列
mutate(test, new = Sepal.Length * Sepal.Width)
2.筛选列
select(test,1)
select(test,c(2,3))
select(test,Sepal.Length)#按列名筛选
3.筛选行
filter(test, Species == "setosa")
filter(test, Species == "setosa"&Sepal.Length>5)
filter(test, Species %in% c("setosa","versicolor"))
4.排序
arrange(test, Sepal.Length)#默认从小到大排序
arrange(test, desc(Sepal.Length))#desc是从大到小
6.汇总
summarise(test,mean(Sepal.Length),sd(Sepal.Length))#计算Sepal.Length的平均值和标准差
group_by(test,Species)
summarise(group_by(test, Species),mean(Sepal.Length),sd(Sepal.Length))
dplyr两个实用技能
dplyr处理关系数据
options(stringsAsFactors = F)
test1 <- data.frame(x = c('b','e','f','x'),
z = c("A","B","C",'D'),
stringsAsFactors = F)
test1
test2 <- data.frame(x = c('a','b','c','d','e','f'),
y = c(1,2,3,4,5,6),
stringsAsFactors = F)
test2
inner_join(test1,test2,by="x")
left_join(test1,test2,by = "x")
left_join(test2,test1,by = 'x')