package處理數(shù)據(jù)
鏡像設(shè)置
- R的包主要來源于CRAN網(wǎng)站和Biocductor,生信主要來源于Biochuctor
- 鏡像代碼設(shè)置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") - tools=>Global options=>packages
包的加載
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)
dplyr 包
- dplyr是一個(gè)dplyr包主要用于數(shù)據(jù)清洗和整理,主要功能有:行選擇、列選擇、統(tǒng)計(jì)匯總、數(shù)據(jù)框交集等是非常高效、友好的數(shù)據(jù)處理包。
-
test <- iris[c(1:2,51:52,101:102),]iris 是R內(nèi)置的一個(gè)數(shù)據(jù)集。 - dplyr五個(gè)基礎(chǔ)函數(shù)
- mutate(),新增列,
mutate(test, new = Sepal.Length * Sepal.Width) - select(),按列篩選,
- 按列號篩選
select(test,1),# 多列:select(test,C(1,5)) - 按列名篩選
select(test, Petal.Length, Petal.Width)
- 按列號篩選
- filter()篩選行 filter詳解
- 篩選1個(gè)
filter(test, Species == "setosa") - 篩選指定
filter(test, Species == "setosa"&Sepal.Length > 5 ) - 篩選
filter(test, Species %in% c("setosa","versicolor"))
- 篩選1個(gè)
- arrange(),按某1列或某幾列對整個(gè)表格進(jìn)行排序,
arrange(test, Sepal.Length)默認(rèn)從小到大排序arrange(test, desc(Sepal.Length))#用desc從大到小 - summarise():匯總計(jì)算平均值,標(biāo)準(zhǔn)差,中位數(shù)等。
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計(jì)算Sepal.Length的平均值和標(biāo)準(zhǔn)差 - group_by 定義分組變量,與summarise合用可高效處理數(shù)據(jù)
先按照Species分組,計(jì)算每組Sepal.Length的平均值和標(biāo)準(zhǔn)差group_by(test, Species)summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
- mutate(),新增列,
- count統(tǒng)計(jì)某列的unique值
count(test,Species)把重復(fù)元素或行給刪除的向量、數(shù)據(jù)框
管道操作
- 什么是管道操作?一個(gè)高效的管道操作工具包,通過管道的連接方式,讓數(shù)據(jù)或表達(dá)式的傳遞更高效
- 安裝
magrittr包install ("magrittr") - 加載
library(magrittr) - %>% 左邊程序傳遞給右邊
test %>% group_by(Species) %>% summarise(mean(Sepal.Length), sd(Sepal.Length))
處理關(guān)系 lianjie
- 內(nèi)連inner_join,取交集
inner_join(test1, test2, by = "x")by="x"表示變量為x列 - 左連保留左邊及交集,
left_join(test1, test2, by = 'x'),還有右邊連接 - 全連取并集,
full_join( test1, test2, by = 'x') - 篩選連接匹配觀測的方式與合并連接相同,但前者影響的是觀測,而不是變量。# 行表示觀測,列表示變量。
- semi_join(x, y): 保留 x 表中與 y 表中的觀測相匹配的所有觀測。
semi_join(x = test1, y = test2, by = 'x') - anti_join(x, y): 丟棄 x 表中與 y 表中的觀測相匹配的所有觀測。```anti_join(x = test2, y = test1, by = 'x')
- semi_join(x, y): 保留 x 表中與 y 表中的觀測相匹配的所有觀測。
- 簡單合并:在相當(dāng)于base包里的cbind()函數(shù)和rbind()函數(shù);注意,
- bind_rows()函數(shù)需要兩個(gè)表格列數(shù)相同,橫向合并
bind_rows(test1, test2) - bind_cols()函數(shù)則需要兩個(gè)數(shù)據(jù)框有相同的行數(shù),縱向合并
bind_cols(test1, test3)
- bind_rows()函數(shù)需要兩個(gè)表格列數(shù)相同,橫向合并