R包學(xué)習(xí)和示例
學(xué)習(xí)R包
學(xué)習(xí)R語言最主要的目的是以后利用它的圖表功能以及bioconductor中多種生信分析的R包富寿。
CRAN是R默認(rèn)使用的R包倉庫盔然,install.packages()只能用于安裝發(fā)布在CRAN上的包。此外還有幾個(gè)軟件包倉庫讨盒,而Bioconductor是基因組數(shù)據(jù)分析相關(guān)的軟件包倉庫解取,需要用專門的命令進(jìn)行安裝。
--引用來源于簡書文章
注:以下示例來自于微信公眾號 生信星球
- 安裝包是否可以從CRAN下載可以用命令
options()$repos
檢驗(yàn) - 安裝包是否可以從Bioc下載可以用
options()$BioC_mirror
檢驗(yàn) - 配置鏡像源
-
file.edit('~/.Rprofile')
啟動Rprofile 編輯文件 - 輸入以下兩行命令運(yùn)行并保存(也可以使用別的鏡像網(wǎng)站)
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) # repos指包所在的網(wǎng)址催植,對應(yīng)清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") # 對應(yīng)中科院鏡像源
之后重啟Rstudio就可以不必反復(fù)設(shè)置鏡像源
安裝R包
安裝命令是install.packages(“包”)
或BiocManager::install(“包”)
取決于安裝的包存在于CRAN 還是Bioc
加載R包
library(包)
require(包)
兩個(gè)命令都可以加載R包
dplyr包安裝及操作實(shí)例
設(shè)置好安裝鏡像之后輸入命令
install.packages("dplyr")
library(dplyr)
使用內(nèi)置數(shù)據(jù)集iris簡化版作為示例數(shù)據(jù)
test <-iris[c(1:2,51:52,101:102),]
dplyr基礎(chǔ)函數(shù)操作實(shí)例(基于上述iris示例數(shù)據(jù))
操作示例來源 微信公眾號 生信星球
- mutate(),新增列
mutate(test, new = Sepal.Length * Sepal.Width)
1
- select(),按列篩選
select(test,1)
2.1
select(test,c(1,5))
2.2
select(test,Sepal.Length)
2.3
- 按列名篩選
select(test, Petal.Length, Petal.Width)
或者
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))
3.
- filter()篩選行
filter(test, Species == "setosa")
4.1
filter(test, Species == "setosa"&Sepal.Length > 5 )
4.2
filter(test, Species %in% c("setosa","versicolor"))
4.3
- arrange(),按某1列或某幾列對整個(gè)表格進(jìn)行排序
arrange(test, Sepal.Length)#默認(rèn)從小到大排序
5.1
arrange(test, desc(Sepal.Length))#用desc從大到小
5.2
- summarise():匯總(結(jié)合 `group_by``操作)
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計(jì)算Sepal.Length的平均值和標(biāo)準(zhǔn)差
6.1
先按照Species分組肮蛹,計(jì)算每組Sepal.Length的平均值和標(biāo)準(zhǔn)差
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
6.2
PS:stringsAsFactors=FALSE就是不變成屬性數(shù)據(jù),按字符串讀入
dplyr的進(jìn)階操作(同樣基于上述iris實(shí)例)
dplyr進(jìn)階