學(xué)習(xí)R包
轉(zhuǎn)自生信星球?qū)W習(xí)筆記
一、安裝和加載R包
1.鏡像設(shè)置
方法有三
1) 初級(jí)模式——Rstudio的程序設(shè)置
Tools---Global Options---Packages---Change
下拉列表選擇一個(gè)離自己近一點(diǎn)的鏡像

image.png
這個(gè)是CRAN的鏡像,下載Bioconductor的包不適用,且受網(wǎng)速限制,options()$repos來檢驗(yàn)鏡像
2)升級(jí)模式——運(yùn)行代碼
# options函數(shù)就是設(shè)置R運(yùn)行過程中的一些選項(xiàng)設(shè)置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #對(duì)應(yīng)清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #對(duì)應(yīng)中科大源
# 當(dāng)然可以換成其他地區(qū)的鏡像
下載Bioconductor還是會(huì)回到官方鏡像,可以查詢options()$BioC_mirror 試試
3)高級(jí)模式
R的配置文件 .Rprofile,可避免每次打開Rstudio都要運(yùn)行一遍鏡像配置
首先用file.edit()來編輯文件:
file.edit('~/.Rprofile')
然后運(yùn)行升級(jí)模式的兩行options代碼
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
最后保存=》重啟Rstudio,再運(yùn)行一下:options()BioC_mirror即可
2.安裝
install.packages(“包”)
BiocManager::install(“包”)
3. 加載
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)
test <- iris[c(1:2,51:52,101:102),]
三、dplyr五個(gè)基礎(chǔ)函數(shù)
1.mutate(),新增列
先運(yùn)行上述代碼
install.packages("dplyr")
library(dplyr)
然后賦值數(shù)據(jù)集,新增列函數(shù)

image.png
2.select(),按列篩選
(1)按列號(hào)篩選

image.png
----新增多列

image.png
----新增列用列名

image.png
(2)按列名篩選

image.png
3.filter()篩選行

image.png
4.arrange(),按某1列或某幾列對(duì)整個(gè)表格進(jìn)行排序

image.png
5.summarise():匯總
對(duì)數(shù)據(jù)進(jìn)行匯總操作,結(jié)合group_by使用實(shí)用性強(qiáng)

image.png
四、dplyr兩個(gè)實(shí)用技能
1:管道操作 %>% (cmd/ctr + shift + M)

image.png
2:count統(tǒng)計(jì)某列的unique值

image.png
五、dplyr處理關(guān)系數(shù)據(jù)
即將2個(gè)表進(jìn)行連接,注意:不要引入factor

image.png
1.內(nèi)連inner_join,取交集

image.png
2.左連left_join

image.png
3.全連full_join

image.png
4.半連接:返回能夠與y表匹配的x表所有記錄semi_join

image.png
5.反連接:返回?zé)o法與y表匹配的x表的所記錄anti_join

image.png
6.簡單合并
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)