第一步_安裝和加載R包
01_設(shè)置鏡像
# 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)中科大源
02_安裝R包
安裝R包使用的函數(shù)取決于下載的地址
install.packages() # CRAN網(wǎng)站
BiocManager::install() # Bioconductor
03_加載R包
library()
require()
第二步_dplyr包的五個(gè)基礎(chǔ)函數(shù)
test <- iris[c(1:2,51:52,101:102),]
# mutate()新增列
mutate(test, new = Sepal.Length * Sepal.Width) # 新增new列
# select()按列篩選
select(test,1) # 選取第一列
select(test,c(1,5)) # 選取1和5列
select(test, Sepal.Length) # 選取Sepal.Length列
select(test, Petal.Length, Petal.Width) # 選取Petal.Length, Petal.Width兩列
vars <- c("Petal.Length", "Petal.Width") # 選取vars變量中的任意一列
select(test, one_of(vars)) #
# filter()按行篩選
filter(test, Species == "setosa") # 選取setosa的行
filter(test, Species == "setosa"&Sepal.Length > 5 ) # 選取setosa且Sepal.Length > 5的行
filter(test, Species %in% c("setosa","versicolor")) # 選取向量中包含元素的列
# arrange()排序
arrange(test, Sepal.Length) # 按照Sepal.Length列排序,默認(rèn)從小到大
arrange(test, desc(Sepal.Length)) # 用desc()排序順序,從大到小
# summarise()對(duì)數(shù)據(jù)進(jìn)行匯總
summarise(test,
mean(Sepal.Length), # 計(jì)算Sepal.Length的平均值
sd(Sepal.Length)) # 計(jì)算Sepal.Length的標(biāo)準(zhǔn)差
group_by(test, Species) # 先按照Species分三組setosa送丰;versicolor;virginica
summarise(group_by(test,Species),mean(Sepal.Length),sd(Sepal.Length)) # 計(jì)算每組Sepal.Length的平均值和標(biāo)準(zhǔn)差
dplyr兩個(gè)實(shí)用技能
## 管道操作:%>% ,加載任意一個(gè)tidyverse包即可使用
test %>% group_by(Species) %>% summarise(mean(Sepal.Length), sd(Sepal.Length))
## count統(tǒng)計(jì)某列的unique值
count(test,Species)
dplyr處理數(shù)據(jù)關(guān)系
將兩個(gè)表進(jìn)行連接侣滩,注意不要引入因子變量
# 合并兩組向量形成數(shù)據(jù)框
test1 <- data.frame(x = c('b','e','f','x'),
z = c("A","B","C",'D'),
stringsAsFactors = F)
test2 <- data.frame(x = c('a','b','c','d','e','f'),
y = c(1,2,3,4,5,6),
stringsAsFactors = F)
# 內(nèi)連inner_join,取交集
inner_join(test1, test2, by = "x") # test1和test2兩個(gè)數(shù)據(jù)框根據(jù)x列共同元素取交集合并
# 左連left_jion
left_join(test1, test2, by = 'x') # 以test1為標(biāo)準(zhǔn),匹配不到test2的x列,即缺失值
left_join(test2, test1, by = 'x') # 以test2為標(biāo)準(zhǔn),匹配不到test1的x列舔痪,即缺失值
# 全連full_jion
full_join( test1, test2, by = 'x') # test1和test2數(shù)據(jù)框中x列元素全部合并保留
# 半連接:返回test1數(shù)據(jù)框中能夠與test2匹配的x列的元素
semi_join( test1, test2, by = 'x')
# 反連接:返回test1數(shù)據(jù)框中無法與test2匹配的x列的元素
anti_join(x = test1, y = test2, by = 'x')
# 簡單合并,相當(dāng)于cbind()和rbind()函數(shù)
# 注意:bind_rows()需要兩個(gè)數(shù)據(jù)框有相同的列锌唾;bind_cols需要兩組數(shù)據(jù)框具有相同的行
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40)) # 4*2
test1
test2 <- data.frame(x = c(5,6), y = c(50,60)) # 2*2
test2
test3 <- data.frame(z = c(100,200,300,400)) # 4*1
test3
bind_rows(test1,test2) # 6*2
bind_cols(test1,test3) # 4*3