同名公主號:BBio
tidyverse包實際上就是一些常用R包的集合顽冶,包括ggplot2(可視化)彪置、dplyr(數(shù)據(jù)操作)逞频、tidyr(數(shù)據(jù))對齊进泼、tibble(更現(xiàn)代的數(shù)據(jù)框)惕稻、stringr(字符串操作)竖共。加載tidyverse包后,其余包中函數(shù)都可以使用俺祠。
//如何理解tidyverse的工作流呢公给?,看完就會有答案锻煌。
diamonds %>% filter(carat < 3) %>% ggplot(mapping = aes(x = carat)) + geom_histogram(binwidth = 0.1)
diamonds2 <- diamonds %>% mutate(y = ifelse(y < 3 | y > 20, NA, y))
//具體應(yīng)用場景舉例
#從panglaodb單細胞marker基因數(shù)據(jù)庫中下載數(shù)據(jù)表格妓布,每個細胞類型對應(yīng)多個marker基因,格式如下
#species official gene symbol cell type nicknames ubiquitousness index product description gene type canonical marker germ la
#Mm Hs CTRB1 Acinar cells CTRB 0.017 chymotrypsinogen B1 protein-coding gene 1 Endoderm Pancreas 1.0 0.957143
#Mm Hs KLK1 Acinar cells Klk6 0.013 kallikrein 1 protein-coding gene 1 Endoderm Pancreas 0.833333 0.314286
#想要整理為每個組織類型對應(yīng)的細胞類型宋梧,以及對應(yīng)的所有marker list應(yīng)該怎么做
#常規(guī)操作匣沼,此處省略,方法有點笨:
data <- read.table("PanglaoDB_markers_27_Mar_2020.tsv.gz", head=T, sep='\t')
panglao_SMC <- data %>% filter(organ == "Smooth muscle", str_detect(species, "Hs")) %>% group_by(cell.type) %>% summarise(geneset = list(official.gene.symbol))
str(panglao_SMC)
#兩行代碼完成捂龄,tidyverse的魅力
#tibble [5 × 2] (S3: tbl_df/tbl/data.frame)
# $ cell.type: chr [1:5] "Airway smooth muscle cells" "Myoepithelial cells" "Myofibroblasts" "Pulmonary vascular smooth muscle cells" ...
# $ geneset :List of 5
# ..$ : chr [1:4] "NOG" "ACTA2" "FOXF1" "GATA5"
# ..$ : chr [1:26] "SFN" "ACTA2" "CNN1" "CA3" ...
# ..$ : chr [1:9] "CDH11" "DES" "PALLD" "ACTA2" ...
# ..$ : chr [1:2] "ANGPT1" "PDGFRB"
# ..$ : chr [1:6] "ACTA2" "MYH11" "PDGFRB" "SEMA3D" ...
//安裝及資料
#https://github.com/tidyverse/tidyverse
# Install from CRAN
install.packages("tidyverse")
# Or the development version from GitHub
# install.packages("devtools")
devtools::install_github("tidyverse/tidyverse")
#https://r4ds.had.co.nz/index.html:學習資源
#ls("package:dplyr")
//dplyr包的主要函數(shù)
library(nycflights13) #數(shù)據(jù)集
library(tidyverse)
flights #測試數(shù)據(jù)释涛,tibble格式,后文詳細介紹
ls("package:dplyr") #查看dplyr包中所有函數(shù)
#%>%:管道符
#將數(shù)據(jù)從左邊傳入右邊倦沧,有大用處唇撬。x %>% f(y) 相當于 f(x, y), x %>% f(y) %>% g(z) 相當于 g(f(x, y), z)
c(1,2,3) %>% mean()
#filter:針對行的數(shù)據(jù)過濾
#可以支持多個篩選條件,以運算符作為標準
filter(flights, month == 1, day == 1)
filter(flights, month == 11 | month == 12)
filter(flights, month %in% c(11, 12))
filter(flights, !is.na(dep_delay))
#arrange:針對行的數(shù)據(jù)排序
#可以支持根據(jù)多列數(shù)據(jù)進行排序
arrange(flights, year, month, day)
arrange(flights, desc(dep_delay)) #降序
#select:針對列的數(shù)據(jù)篩選
#直接使用列名展融,支持多列篩選窖认,切片篩選,或者去除某些列告希。也可以使用默認函數(shù)進行篩選扑浸。
select(flights, year, month, day)
select(flights, year:day)
select(flights, -(year:day))
select(flights, starts_with("abc"))
select(flights, contains("a"))
#rename:重命名列名
rename(flights, tail_num = tailnum)
#mutate:增加列
#可以基于已有數(shù)據(jù),通過計算增加新列
flights_sml <- select(flights, year:day, ends_with("delay"), distance, air_time)
mutate(flights_sml, gain = dep_delay - arr_delay, speed = distance / air_time * 60)
mutate(flights_sml, gain = dep_delay - arr_delay, hours = air_time / 60, gain_per_hour = gain / hours)
transmute(flights, gain = dep_delay - arr_delay, hours = air_time / 60, gain_per_hour = gain / hours) #只保留新列
#min_rank:排名
y <- c(1, 2, 2, NA, 3, 4)
min_rank(y)
#summarise:總結(jié)
#和group_by連用對不同的分組數(shù)據(jù)進行總結(jié)燕偶。group_by改變原數(shù)據(jù)喝噪,只是添加了分組信息。
by_day <- group_by(flights, year, month, day)
summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))
#管道符連接多個函數(shù)指么,可讀性瞬間提升
delays <- flights %>%
group_by(dest) %>%
summarise(
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
) %>%
filter(count > 20, dest != "HNL")
//dplyr包的其它函數(shù)
#between酝惧,返回邏輯值
between(1:12, 7, 9)
#group_split:分組
data.frame(celltype=rep(c("T cells", "B cells"), each=2), marker=c("CD3D", "CD2", "MS4A1", "CD79A")) %>% group_by(celltype) %>% group_split()
#across:選擇多列榴鼎,并用函數(shù)處理
iris %>% as_tibble() %>% mutate(across(c(Sepal.Length, Sepal.Width), round))
#if_any,篩選
iris %>% filter(if_any(ends_with("Width"), ~ . > 4))
iris %>% filter(if_all(ends_with("Width"), ~ . > 2))
#inner_join:按列合并倆數(shù)據(jù)集中的行晚唇,取交集巫财。其余為左合并,右合并缺亮,并集合并翁涤。
band_members %>% inner_join(band_instruments, by="name")
band_members %>% left_join(band_instruments)
band_members %>% right_join(band_instruments)
band_members %>% full_join(band_instruments)
#根據(jù)兩個數(shù)據(jù)集中匹配關(guān)系過濾行
#semi_join(x, y) keeps all observations in x that have a match in y.
#anti_join(x, y) drops all observations in x that have a match in y.
top_dest <- flights %>% count(dest, sort = TRUE) %>% head(10)
top_dest
flights %>% semi_join(top_dest)
#pull:提取某列桥言,分別為最后一列萌踱,第一列,cyl列号阿,并輸出為向量
mtcars %>% pull(-1)
mtcars %>% pull(1)
mtcars %>% pull(cyl)
#slice:切片并鸵,篩選行
slice(mtcars, -(1:4))
mtcars %>% slice_min(mpg, n = 5)
//tibble包中的主要函數(shù)
tibble格式的數(shù)據(jù)和data.frame非常相似,但是更加現(xiàn)代化扔涧,更方便使用园担。tibble格式數(shù)據(jù)默認只輸出前10行,以及適應(yīng)屏幕的列枯夜,對大數(shù)據(jù)友好弯汰。列名還支持特殊字符,非常人性化湖雹。
library(tidyverse)
#格式轉(zhuǎn)換
class(iris)
iris_tibble <- as_tibble(iris)
class(iris_tibble)
iris <- as.data.frame(iris_tibble)
#輸出所有列
nycflights13::flights %>% print(n = 10, width = Inf)
#取子集
df <- tibble(
x = runif(5),
y = rnorm(5)
)
df$x #向量
df[["x"]] #向量
df["x"] #tibble
#添加行列
df <- tibble(x = 1:3, y = 3:1)
df %>% add_row(x = 4, y = 0)
df %>% add_column(z = -1:1, w = 0)
#行名轉(zhuǎn)給為數(shù)據(jù)咏闪,列轉(zhuǎn)為行名
mtcars_tbl <- rownames_to_column(mtcars, var = "car") %>% as_tibble()
mtcars_tbl
column_to_rownames(mtcars_tbl, var = "car") %>% head()
//tidyr包中的主要函數(shù)
library(tidyverse)
#pivot_longer:寬數(shù)據(jù)轉(zhuǎn)為長數(shù)據(jù)
table4a
table4a %>% pivot_longer(c(`1999`, `2000`), names_to = "year", values_to = "cases")
#pivot_wider:寬數(shù)據(jù)轉(zhuǎn)為長數(shù)據(jù)
table2
table2 %>% pivot_wider(names_from = type, values_from = count)
#seprate:分割一列為多列,可以指定分隔符或者分割的位置
table3 %>% separate(rate, into = c("cases", "population"), sep="/")
table3 %>% separate(year, into = c("century", "year"), sep = 2)
//stringr中的主要函數(shù)
str_length(c("a", "R for data science", NA))
#str_c:連接字符串
str_c("x", "y")
str_c("x", "y", sep = ", ")
str_c("prefix-", c("a", "b", "c"), "-suffix")
#取子集
x <- c("Apple", "Banana", "Pear")
str_sub(x, 1, 3)
#
str_to_lower(x)
str_to_upper(c("i", "?"))
str_sort(x, locale = "en")
#匹配
x <- c("apple", "banana", "pear")
str_detect(x, "e")
#統(tǒng)計次數(shù)
x <- c("apple", "banana", "pear")
str_count(x, "a")
#替換
x <- c("apple", "pear", "banana")
str_replace(x, "[aeiou]", "-")
str_replace_all(x, "[aeiou]", "-")
#分割
sentences %>% head(5) %>% str_split(" ")