R之tidyverse包使用

数据读取

1
2
3
library(magrittr)
library(tidyverse)
data <- readr::read_tsv("test.tsv") %>% as.data.frame() # %>%为管道操作符

合并数据

1
2
3
4
5
6
7
8
9
# 左连接 (x和y根据sample匹配, 将y中匹配的列添加到x, 保留x)
left_join(x, y, by = "sample")
left_join(x, y, by = c("sample1" = "sample2")) # x和y中没有相同的列名
# 右连接 (保留y)
right_join(x, y, by = "sample")
# 全连接 (x和y中的的内容都保留)
full_join(x, y)
# 内连接 (保留x和y的交集)
inner_join(x, y)

数据列选择select

1
2
3
4
5
6
7
8
9
10
11
# 选择Gene和sample表中的ID列的列
data %>% select(Gene, c(sample$ID))
# 选择Gene到sample之间的列 (包括Gene和sample列)
data %>% select(Gene:sample)
# 改变列的顺序
data %>% select(sample, Gene)
# 删除Gene列 (相当于反选)
data %>% select(-Gene)
data %>% select(!Gene)
# 选取以A开头并且不以Z结尾的列
data %>% select(starts_with("A") & !ends_with("Z"))

数据列添加mutate

1
2
3
4
5
6
7
8
9
10
# 添加值为x列+y列的新列z
data %>% mutate(z = x + y)
# 添加的z列放到x列前 (后用after)
data %>% mutate(z = x + y, .before = x)
# 保留所有列 ("used"使用过的列, "unused"未使用过的列, "none"不保留原来任何列)
data %>% mutate(z = x + y, .kepp = "all")
# 除sample列其余列全部转为因子
data %>% mutate(across(!sample, as.factor))
# 新增上调和下调基因类型的type列
data %>% mutate(type = case_when(FDR < 0.05 & logFC > 0 ~ "up", FDR < 0.05 & logFC < 0 ~ "down"))

数据行筛选filter

1
2
3
4
5
6
7
8
9
10
# 筛选group列为normal的数据
filter(data, group == 'normal')
# 筛选Gene列大于Gene列平均值的列
filter(data, Gene > mean(Gene))
# 筛选sample列不包含A和B的数据
filter(data, !sample %in% c('A', 'B'))
# 删除Gene列中含有NA的数据
data %>% drop_na(Gene)
# 根据所有列删除重复的数据 (可以指定列,默认所有列)
data %>% distinct()

数据行操作rowwsie

1
2
3
4
# 计算每行的均值
data %>% rowwise(gene) %>% mutate(avg = mean(c_across(is.numeric)))
# 将Gene列按;分隔形成多行数据
data %>% separate_rows(Gene, sep = ";")

数据分组group_by

1
2
# 按照group列分组
data %>% group_by(group)

数据排序arrange

1
2
# 按Gene值升序排序 (desc(Gene)为降序排序)
data %>% arrange(Gene)

数据汇总summarize

1
2
3
4
# 按group分组统计A和B的中位数
data %>% group_by(group) %>% summarise(A = median(A), B = median(B))
# 以均值作为gene的表达值
data %>% group_by(gene) %>% summarise(across(where(is.numeric), mean))
Author: Giftbear
Link: https://giftbear.github.io/2023/08/17/R之tidyverse包使用/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.