Day6.jpg
本文以dplyr包为例
镜像设置
初级模式
在Rstudio中设置CRAN镜像,通过options()$repos来检验。(但是如果要下载Bioconductor的包,这个镜像是没有办法用的!!!)升级模式
自定义CRAN和Bioconductor的下载镜像
#options函数就是R运行过程中的一些设置选项
options("repos"=c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
-
高级模式
需要用到R的配置文件.Rprofile
file.edit('~/.Rprofile')
options("repos"=c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源`
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
#保存file
#重启Rstudio
#再运行options()$repos和options()$BioC_mirror就发现已经配置好了
安装(需要联网)
install.packages("包名")
#BiocManager::install("包名")
#取决于安装的包存在于CRAN网站还是Bioconductor
加载(两种方式)
library(包名)
require(包名)
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)
test<-iris[c(1:2,51:52,101:102),]
函数
mutate():新增列
mutate(test,new=Sepal.Length*Sepal.Width) #新增一列new,值为Sepal.Length*Sepal.Width
select():按列筛选
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))
#也可以是
select(test,all_of(vars))
注:
最好不要用select(test,vars)
会提示Use ‘all_of(vars)’ instead of ’vars‘ to silence this message.
- filter():筛选行
filter(test, Species=="setosa")
filter(test, Species=="setosa"&Sepal.Length>5)
filter(test, Species %in% c("setosa","versicolor")
- arrange():按某一列或某几列对整个表格进行排序
arrange(test, Sepal.Length) #默认根据Sepal.Length值从小到大排序
arrange(test, desc(Sepal.Length)) #desc表示从大到小
- summaries():汇总(可结合group_by)
summaries(test, mean(Sepal.Length), sd(Sepal.Length)) #计算Sepal.Length的均值和标准差
group_by(test,Species) #按Species分组
summaries(group_by(test,Species) , mean(Sepal.Length), sd(Sepal.Length)) ##计算根据物种分组后的Sepal.Length均值和标准差
dplyr两个实用技能
- 管道操作%>%(cmd/ctr+shift+M)
test %>% group_by(Species) %>% summaries(mean(Sepal.Length), sd(Sepal.Length))
-
count():统计某列的unique值
count(test, Species) #一共有多少种品种,以及对应的频数
dplyr处理关系数据
- 两个表进行连接,注意不要引入factor
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:内部连接,取交集
inner_join(test1,test2,by="x") #取两个表的x交集
left_join:左连接
left_join(test1,test2,by="x") #根据test1的x进行连接
left_join(test2,test1,by="x") #根据text2的x进行连接
full_join:全连接
full_join(test1, test2,by="x")
semi_join:半连接,返回无法与y表匹配的x表的所有记录
semi_join(x=test1,y=test2,by="x")
bind_rows:行连接,两个表格列数相同;bind_cols:列连接,两个数据框行数相同
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
test1
test2 <- data.frame(x = c(5,6), y = c(50,60))
test2
test3 <- data.frame(z = c(100,200,300,400))
test3
bind_rows(test1, test2)
bind_cols(test1,test3)