學習R包
1.安裝和加載R包
1.1.鏡像設置
1.2.安裝
- install.packages("包")(R包存在于CRAN網(wǎng)站)
-
BiocManager::install("包")(R包存在于Biocductor)
具體需要的包在哪里可以直接在google上搜索
1.3.加載
- library(包)
-
require(包)
兩個命令均可
以安裝dplyr為例,安裝加載三部曲的命令行為:
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)
以下演示用內(nèi)置數(shù)據(jù)集iris的簡化版進行
test <- iris[c(1:2,51:52,101:102),]

image.png
2.dplyr五個基礎函數(shù)
2.1.mutate(),新增列
-
mutate(test, new = Sepal.Length * Sepal.Width)
新增一列new
image.png
2.2.select(),按列篩選
2.2.1.按列號篩選
-
select(test,1)
image.png -
select(test,c(1,5))
image.png
2.2.2.按列名篩選
-
select(test, Petal.Length, Petal.Width)
image.png -
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))
image.png
2.3.filter()篩選行
-
filter(test, Species == "setosa")
image.png -
filter(test, Species == "setosa"&Sepal.Length > 5 )
image.png -
filter(test, Species %in% c("setosa","versicolor"))
image.png
2.4.arrange(),按某1列或某幾列對整個表格進行排序
-
arrange(test, Sepal.Length)默認從小到大排序
image.png -
arrange(test, desc(Sepal.Length)) 用desc從大到小
image.png
2.5.summarise():匯總
-
summarise(test, mean(Sepal.Length), sd(Sepal.Length)) 計算Sepal.Length的平均值和標準差
image.png -
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length)) 先按照Species分組,計算每組Sepal.Length的平均值和標準差
image.png
image.png
3.dplyr兩個實用技能
3.1.管道操作 %>% (cmd/ctr + shift + M)
即在連續(xù)操作中用幾句簡單的命令進行操作,避免了冗長的命令行
解析
-
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
image.png
可得到與上一個操作一樣的結(jié)果
3.2.count統(tǒng)計某列的unique值
-
count(test,Species)
image.png
4.dplyr處理關系數(shù)據(jù)
先準備兩個表格
test1
-
test1 <- data.frame(x = c('b','e','f','x'),
z = c("A","B","C",'D'),
stringsAsFactors = F)
image.png
test2 -
test2 <- data.frame(x = c('a','b','c','d','e','f'),
y = c(1,2,3,4,5,6),
stringsAsFactors = F)
image.png
4.1.內(nèi)連inner_join,取交集
-
inner_join(test1, test2, by = "x")
image.png
4.2.左連left_join
-
left_join(test1, test2, by = "x")
image.png -
left_join(test2, test1, by = "x")
image.png
4.3.全連full_join
-
full_join( test1, test2, by = "x")
image.png
4.4.半連接:返回能夠與y表匹配的x表所有記錄semi_join
-
semi_join(x = test1, y = test2, by = "x")
image.png
4.5.反連接:返回無法與y表匹配的x表的所記錄anti_join
-
anti_join(x = test2, y = test1, by = "x")
image.png
4.6.簡單合并
bind_rows()函數(shù)需要兩個表格列數(shù)相同,而bind_cols()函數(shù)則需要兩個數(shù)據(jù)框有相同的行數(shù)
先準備三個數(shù)據(jù)集
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))

image.png
test2 <- data.frame(x = c(5,6), y = c(50,60))

image.png
test3 <- data.frame(z = c(100,200,300,400))

image.png
-
bind_rows(test1, test2)
image.png -
bind_cols(test1, test3)
image.png
























