今天的學(xué)習(xí)內(nèi)容是R包安裝和dplyr函數(shù)的運(yùn)用
一混巧、安裝和加載R包
鏡像設(shè)置
1.Tools-Options-Packages設(shè)置CRAN的鏡像,單不能下載Bioconductor的包
2.R的配置文件 .Rprofile
用file.edit('~/.Rprofile')來編輯文件,在編輯器輸入options代碼
options("repos" = c(CRAN="[https://mirrors.tuna.tsinghua.edu.cn/CRAN/
(https://mirrors.tuna.tsinghua.edu.cn/CRAN/)"))#對(duì)應(yīng)清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #對(duì)應(yīng)中科大源
然后保存,重啟Rstudio,運(yùn)行options()BioC_mirror查看
3.安裝
install.packages(“包”)或者BiocManager::install(“包”)
取決于安裝的包存在于CRAN還是Biocductor
4.加載
命令library(包)或require(包)
install.packages("dplyr")
library(dplyr)
二蚜厉、dplyr五個(gè)基礎(chǔ)函數(shù)
1.mutate(),新增列
mutate(test, new = Sepal.Length * Sepal.Width)
2.select(),按列篩選
(1)按列號(hào)篩選
select(test,1)
select(test,c(1,5))
[圖片上傳中...(6.png-636659-1631843108966-0)]
(2)按列名篩選
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列或某幾列對(duì)整個(gè)表格進(jìn)行排序
arrange(test, Sepal.Length)#默認(rèn)從小到大排序
arrange(test, desc(Sepal.Length))#用desc從大到小
5.summarise():匯總
對(duì)數(shù)據(jù)進(jìn)行匯總操作,結(jié)合group_by使用實(shí)用性強(qiáng)
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計(jì)算Sepal.Length的平均值和標(biāo)準(zhǔn)差
group_by(test, Species)# 先按照Species分組
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))#計(jì)算每組Sepal.Length的平均值和標(biāo)準(zhǔn)差
三、dplyr兩個(gè)實(shí)用技能
1.:管道操作 %>% (cmd/ctr + shift + M)
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
2.:count統(tǒng)計(jì)某列的unique值
count(test,Species)
四畜眨、dplyr處理關(guān)系數(shù)據(jù)
即將2個(gè)表進(jìn)行連接
options(stringsAsFactors = F)#不變成屬性數(shù)據(jù),按字符串讀入
創(chuàng)建test1术瓮,test2數(shù)據(jù)框
1.內(nèi)連inner_join,取交集
inner_join(test1, test2, by = "x")
2.左連left_join
left_join(test1, test2, by = 'x')
3.全連full_join
full_join( test1, test2, by = 'x')
4.半連接:返回能夠與y表匹配的x表所有記錄semi_join
semi_join(x = test1, y = test2, by = 'x')
5.反連接:返回?zé)o法與y表匹配的x表的所記錄anti_join
anti_join(x = test2, y = test1, by = 'x')
6.簡(jiǎn)單合并
在相當(dāng)于base包里的cbind()函數(shù)和rbind()函數(shù);注意康聂,bind_rows()函數(shù)需要兩個(gè)表格列數(shù)相同,而bind_cols()函數(shù)則需要兩個(gè)數(shù)據(jù)框有相同的行數(shù)
bind_rows(test1, test2)
bind_cols(test1, test3)