学习R包
1、安装和加载R包
- 镜像设置
为了加速包的下载,一般会配置一个国内镜像,可以在Rstudio的程序设置中直接选择,也可以在R的配置文件“ .Rprofile”进行添加,具体步骤如下
file.edit('~/.Rprofile')
# options函数就是设置R运行过程中的一些选项设置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
最后保存=》重启Rstudio,这时你再运行一下:options()$repos
和options()$BioC_mirror
就发现已经配置好了
参考生信星球你还在每次配置Rstudio的下载镜像吗?
- 安装R包
R包安装命令是
install.packages(“包”)
或者BiocManager::install(“包”)
- 加载R包
library(包)
require(包)
- 例:安装加载软件
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)
2、dplyr五个基础函数
#1.mutate(),新增列
library(dplyr)
test <- iris[c(1:2,51:52,101:102),]
mutate(test, new = Sepal.Length * Sepal.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, Sepal.Length)#默认从小到大排序
arrange(test, desc(Sepal.Length))#用desc从大到小
#5.summarise():汇总
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))
3、dplyr两个实用技能
#1:管道操作 %>% (cmd/ctr + shift + M)
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
#2:count统计某列的unique值
count(test,Species)
4、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')
full_join( test1, test2, by = 'x')
semi_join(x = test1, y = test2, by = 'x')
anti_join(x = test2, y = test1, by = 'x')
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)
详细教程见Day6-学习R包